-
Check if an Integer
In main()
say you have something like this:
Code:
int main(){
int a;
cout << "enter an integer: " ;
cin >> a;
CheckIfInt(a);
return 0;
}
void CheckIfInt(int b)
{
/// ?????
}
How would you go about checking if what the user entered is an integer? If the user not entered an integer, then repromt the user. how would one do this? I've tried coverting to ASCII, but that doesn't seem to help.
-
>How would you go about checking if what the user entered is an integer?
a has integer type, so if the request for input fails then the user didn't enter an integer:
Code:
for ( ; ; ) {
cout<<"Enter an integer: ";
// Success
if ( cin>> a )
break;
else {
cout<<"Not an integer\n";
// Clear the error state
cin.clear();
// Remove the bad characters
cin.ignore(magic_number, '\n');
}
}