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

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

#include 
#include 
#include 

// 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;
}

Here is what the above code is Doing:
1. The function lettersOrSpaces() is defined. It takes a string as an argument and returns a bool.
2. The function loops through the string and checks each character to see if it is a letter or a space.
3. If the character is not a letter or a space, the function returns false.
4. If the function loops through the entire string and does not find a character that is not a letter or a space, it returns true.
5. The main() function asks the user to enter a town name.
6. The main() function calls the lettersOrSpaces() function and passes the town name as an argument.
7. If the lettersOrSpaces() function returns true, the main() function prints the town name.
8. If the lettersOrSpaces() function returns false, the main() function asks the user to enter the town name again.
9. The main() function loops back to step 6 and repeats the process until the user enters a town name that contains only letters and spaces.

Similar Posts