Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

how to validate if all characters enetred in a string are alphabets and then reprompt user

#include <iostream>
#include <string>
#include <cctype>

// check for only alphabetical letters in string (or spaces)
bool lettersOrSpaces(const std::string& str)
{
    for (size_t i = 0; i < str.size(); i++)
    {
        // make sure each character is A-Z or a space
        if (! std::isalpha(str[i]) && ! std::isspace(str[i]))
        {
            return false; ///< at least one "no match"
        }
    }
    return true;  ///< all characters meet criteria
}

int main()
{
    std::string townName;
    std::cout << "Enter name of town: ";
    while (std::getline(std::cin, townName) && !lettersOrSpaces(townName))
    {
        std::cout << "Enter the town name - alphabet only: ";
    }
    std::cout << "The name of town is: " << townName << std::endl;

    return 0;
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #validate #characters #enetred #string #alphabets #reprompt #user
ADD COMMENT
Topic
Name
2+1 =