IBTEHAAJ SHAHID IBTEHAAJ SHAHID - 5 months ago 20
C++ Question

How to apply validation on a string variable so that it accept only alphabetic data from the user?

I want to make the user enter alphabetic data only not any numeric or special character data. So how do I apply the validation? For example, in the following code, I want the user to input name and name doesn't include any number or special character. I want to make it accept only alphabetic data.

int main()
{
string str;
cout<<"Enter your name: ";
cin>>str;
}

Answer Source

One way is to use ctype.h or cctype
Functions to determine the type contained in character data

Ex: It accepts only alphabetic nothing else even space

std::string ui; // user input
std::getline( std::cin, ui );

bool vi = true; // validate input
for( const char& chr : ui ){
    if( !std::isalpha( chr ) ){
        vi = false;
        break;
    }
}

if( vi ){
    std::cout << "okay\n";
} else {
    std::cout << "NOT!\n";
}

the other one is to use std::regex
Regular expressions library (C++11)

Ex: Likewise

std::string ui; // user input
std::getline( std::cin, ui );

bool vi = true; // validate input

//    for( const char& chr : ui ){
//        if( !std::isalpha( chr ) ){
//            vi = false;
//            break;
//        }
//    }

vi = std::regex_match( ui, std::regex( "[A-Za-z]+" ) );

if( vi ){
    std::cout << "okay\n";
} else {
    std::cout << "NOT!\n";
}  

You can find what you need based on these functions or use regexes

isalnum  
isalpha
islower 
isupper 
isdigit 
isxdigit 
iscntrl 
isgraph
isspace 
isblank
isprint
ispunct

NOTE: that the c++11 for-loop in the EX: is equivalent to this:

for( unsigned index = 0; index < ui.size(); ++index ){
    if( !std::isalpha( ui[ index ] ) ){
        vi = false;
        break;
    }
}