This question already has an answer here:
Please read the following code:
#include <iostream>
#include <cstdlib>
int main() {
std::cout << "Please input one integer." << std::endl;
int i;
while (true) {
std::cin >> i;
if (std::cin) {
std::cout << "i = " << i << std::endl;
break;
} else {
std::cout << "Error. Please try again."<< std::endl;
std::cin.ignore();
std::cin.clear();
}
}
std::cout << "Thank you very much." << std::endl;
std::system("pause");
return 0;
}
When I give std::cin an invalid input, such as w
, then Error. Please try again.
is outputed infinitely.
I thought std::cin.ignore
would blank the input stream, and std::cin.clear
would resume it to normal state. So why does the infinite loop happen?
By default, std::basic_istream::ignore()
ignores only 1 character:
basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );
(From http://en.cppreference.com/w/cpp/io/basic_istream/ignore)
More idiomatic use for your case seems to be the one from the example there:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Also, note that you want to call clear()
before the ignore()
call, so the input extraction of ignore()
will succeed instead of returning immediately.
来源:https://stackoverflow.com/questions/38890379/stdcin-infinite-loop-from-invalid-input