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.
Share
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:
If failure occurs and you want to get past the invalid input so that the user can try again, first call
cin.clear(), then eithercin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')to ignore the whole line, orstd::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…