If the number entered is "zzzz" then the rdstate returns a value of 4.
If the number entered is "10zzzz" then the rdstate returns a value of
0, number has a value of 10, and the input stream has "zzzz" in it.
To understand why these happen, we need to understand how the extraction operator (operator>>) works. Here are a few good links to start with:
std::cin and handling invalid input
std::istream::operator>>
One could dig deeper in the following places:
operator>>(std::basic_istream)
std::basic_istream<CharT,Traits>::operator>>
std::num_get<CharT,InputIt>::get, std::num_get<CharT,InputIt>::do_get
In simple terms, when writing to an arithmetic type, the input is parsed character by character as long as the sequence of characters can be exactly interpreted as a value of that type. When it is no longer possible to do so, the parsing stops and the valid value that has been obtained till that point is used.
"zzzz" presents no valid value, while "10zzzz" allows 10
to be parsed.
As far as a solution is concerned, the string stream based answer by dennis could be improved to handle trailing characters as shown here. !myStream.eof()
will evaluate to true if there are trailing characters.
Also, there are other options apart from using a string stream. For e.g., strtol
, std::stoi
.
Also, using an input string stream instead of a string stream in this context will be better. See here.