Hello i want to check in my program if the user instead of typing a digit if he typed something that is not a digit.
so i did this function
void ValidationController::cinError(int *variable){
if(!isdigit(*variable)){
cin.clear();
cin.ignore(256, '\n');
cout <<*variable<<endl;
*variable=0;
cout <<*variable<<endl;
}
}
i call the function like this:
int more;
cin >>more;
cinError(&more);
So my problem is that everytime i give a digit it acts like i didn't.It goes inside if and makes the variable equal to zero.What am i missing here?
Leaving aside the fact that you are using isdigit
incorrectly, it's too late to check for isdigit
anyway, because you are reading an int
. In this situation it is the stream's >>
operator that looks for digits, not your code.
If you want to validate the user input, read the data into a string
, and then use isdigit
on its components, like this:
string numString;
getline(cin, numString);
for (int i = 0 ; i != numString.length() ; i++) {
if (!isdigit((unsigned char)numString[i])) {
cerr << "You entered a non-digit in a number: " << numString[i] << endl;
}
}
// Convert your validated string to `int`
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments