#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
int main()
{
{
// generate an error if non-alpha characters are entered
std::string name ;
std::cout << "enter your first name (only alpha characters please): " ;
std::cin >> name ;
// https://en.cppreference.com/w/cpp/algorithm/all_any_none_of
// http://www.stroustrup.com/C++11FAQ.html#lambdaif( std::any_of( name.begin(), name.end(), []( char c ) { return !std::isalpha(c) ; } ) )
std::cout << "error: name contains invalid characters\n" ;
else
std::cout << "fine. name: " << name << '\n' ;
}
{
// ignore non-alpha characters that are entered
std::string name ;
std::cout << "enter your first name (only alpha characters please): " ;
char c ;
while( std::cin.get(c) && std::isspace(c) ) ; // skip leading white space
doif( std::isalpha(c) ) name += c ; // append only alpha characters to name
while( std::cin.get(c) && !std::isspace(c) ) ; // till a white space is encountered
if( name.empty() ) std::cout << "error: name can't be empty\n" ;
else std::cout << "fine. name: " << name << '\n' ;
}
}
Line 3-4: If the length of the string is 0, it's invalid. This could be the result if cin fails for whatever reason.
Line 6-10: This is a for loop that is iterating over every character (ch) in the name. If the character is not "alpha" (a letter from A to Z), it returns false.
Line 11: Otherwise, if it has looped through every character and finds no non-alpha characters, the name is valid.