Question

I need to read in an int from the user using cin but print an error message if a string is entered instead. I have been trying to make it work using an if statement with cin.fail() which works well if only characters are entered. However, if the user enters something like 3sadi it seems to read in the 3 and leave the rest of the string in the buffer, which doesn't give me the error message because the cin.fail() flag isn't set. How can I make it so that the error message is still printed if the first character of a string is an int?

int i1;
cin >> i1;
if (cin.fail() == true) {
    cout << "error" << endl; 
}
else{
    cout << "success" << endl;
}

eg. 32 should (and does) print success

red should (and does) print error

3x should print error but is printing success and leaving x in the buffer

How can I make 3x give me the error message? Alternatively I could read it in as a string and cast it to an int and print out the message based on if it failed or succeeded but how do you use type cast errors in a program?

Was it helpful?

Solution

Formatted input of an numeric values succeeds is there is a prefix which contains digits. The streams won't easily allow you to change that behavior (you can change that behavior by using a specialized std::num_get<char> facet but I won't classify that as simple). The easiest approach is probably to check whether the next character (if there is one) happens to be a space (and don't use fail(); you should just use the conversion to a boolean value):

if (std::cin && (std::isspace(std::cin.peek()) || std::cin.eof())) {
    ...
}

Also, don't compare boolean values in conditions to true or false: the result doesn't become more boolean by doing so.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top