Input is type safe in c++ when using IO streams. So when you do something like
int nAge;
std::cin >> nAge;
the compiler finds an overload like std::istream& std::cin::operator >>(int& var)
and since it knows it is working with an int
, it will only store an inputted int
, ie: 5, -121, 1235156141. It does have one one main issue though. If you entered 5a
, then it would get the int
part, the 5
, and leave a
in the stream as it is not an int
. This could be very bad for your following code since there is now a a
just sitting in the buffer. If you asked for another int
, then that would fail as a
is not an int
.
To get around this problem what you can do is take the input in as a std::string
like you see in the tutorial. When you do that the entire 5a
is read in from the stream and placed into the string. Then stoi
will get the int
part out of it and now you have a valid int
and an empty stream.
So, to sum it all up, if you want better error handling, take your input in as a std::string
. It lets you clear out the buffer and sanitize the input. Sure, it costs more, but if you are dealing with input that processing time is going to be unnoticed by the user.