1

So this is a problem that I've been having since I started programming (Not that long ago. I still don't know why I started with C++). When I have some integer variables and the user's input defines them, if the user inputs something other than an integer the program freaks out and runs an endless loop of the last command it was given. I don't think sample code is needed but if it is I can make a basic example pretty easily.

h3half
  • 226
  • 1
  • 3
  • 16

3 Answers3

5

If you want to know exactly what your mistake was, then we'd need to see your code, but the usual idiom is like this:

int i;
while (std::cin >> i) {
   // do something with the user's input, i
}
if (std::cin.fail()) {
   std::cout << "not a number!\n";
}

If failure occurs and you want to get past the invalid input so that the user can try again, first call cin.clear(), then either cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') to ignore the whole line, or std::string s; std::cin >> s; to ignore a whitespace-separated word.

Beware that because the second case actually constructs the string in memory, the user could input a few gigabytes without a space, and the program will fail. That's usually fine if the input is from a terminal, it's the user's own stupid fault. It might be less fine if the input is from an HTTP request or other untrusted source, so some time in future you might end up worrying about it...

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
1

Check this out Guess the number - Infinite loop when bad read

Community
  • 1
  • 1
George Kastrinis
  • 4,924
  • 4
  • 29
  • 46
0

When programming always, and i mean always, validate your input.

Check if the input you get is sane. What i mean by that if you get something that is supposed to be int check if it is. Convert it if it is not.

If you get a string check if it is in bounds, meaning is it to long, to short, to whatever.

cin

Would be the Term to Google for in your case.

Eduard Thamm
  • 942
  • 1
  • 6
  • 7