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?