开发者

Stopping endless loop when int = (something that's not an integer)

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 mak开发者_如何转开发e a basic example pretty easily.


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...


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜