I have this code snippet that is supposed to test whether the user enters an integer or not. This works if the user enters letters, but not decimals and I’m left wondering why that is. Here’s my code snippet:
Student student;
int id;
while(!(cin >> id))
{
cout << "\nERROR: Please enter a Positive Whole Number" << endl;
cin.clear();
cin.ignore ();
cout << "Enter Student ID: ";
}
Entering A will make it iterate through the while loop, but if I enter 12.5 it drops out of the while loop and keeps going. Isn’t it testing whether it will parse to integer or not? Why is it accepting 12.5 but not characters?
cin>>idwill succeed as long as it finds something it can convert to anint(“12”, in this case). When it reaches something it can’t convert, it stops, but if it’s read anintalready, that counts as success.To check that everything it read was digits, you might want to do something like using
std::getlineto read a line of input into a string, then usestd::isdigitto test whether those are all digits. Testing a conversion toint(by itself) will only tell you that it found something that could be read as an integer, but won’t tell you if that was followed by other things that couldn’t be converted to anint.