2

So I was watching a tutorial on C++. He was explaining a program on is a birthday important. These were the conditions.

1 - 18, 21, 50, > 65 : Important

All others are not important

He used the following code:

std::string sAge = "0";
std::cout << "Enter your age : ";
getline(std::cin, sAge);
int nAge = std::stoi(sAge);

Why not just use the following code to get input from the user instead of the above given code?

int nAge;
std::cin >> nAge;
NathanOliver
  • 150,499
  • 26
  • 240
  • 331
Nishant Kehar
  • 41
  • 1
  • 7
  • 1
    Try it, and type X when it prompts you for input. – Pete Becker Aug 06 '19 at 21:04
  • I don't see a reason for the original code, unless you are trying to explain those functions. – JVApen Aug 06 '19 at 21:04
  • Also depends a lot on what's going on around the code. For example if you find yourself mixing `>>` and `getline`, you'll likely wander into [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – user4581301 Aug 06 '19 at 21:09

1 Answers1

3

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.

NathanOliver
  • 150,499
  • 26
  • 240
  • 331
  • Why not using exception handling instead? Is this recommended in a real world program? or using exception handling? – Maestro Aug 06 '19 at 21:16
  • @Maestro can you please clarify how exactly exception handling will apply here? – SergeyA Aug 06 '19 at 21:19
  • 2
    @Maestro There is a large aversion to exceptions in C++. They are also supposed to be for exceptional occasions. Bad input is nothing exceptional. Users do it all the time. Handling it with normal input processing is generally they way bad input is handled. – NathanOliver Aug 06 '19 at 21:19