c++ - why does my cin loop never end? -
in following code, if user inputs not int
, program goes infinite loop. why happen, , should fix it?
#include <iostream> #include <string> using namespace std; int main() { int i; char str[100]; while (!(cin >> i)) { gets(str); cout << "failure read!" << endl; } cout << "successful read!" << endl; return 0; }
clear error state:
int main() { int i; char str[100]; while (!(cin >> i)) { cin.clear(); cin.getline(str,100); cout << "failure read!" << endl; } cout << "successful read!" << endl; return 0; }
Comments
Post a Comment