std::cin and cin.fail()--infinite loops!

Started by
1 comment, last by hellz 19 years, 8 months ago
Have I missed something stupid? If you enter a non-int, it goes into an infinite loop. (Shouting boo, boo, boo at my stupidity too!)
Quote: #include <iostream> using namespace std; int main() { int i; std::cin >> i; while(cin.fail()) { cout << "boo\n"; std::cin >> i; } cout << "yay\n"; return 0; }
Thanx! -Stacy
Advertisement
Try this:

#include <iostream>using namespace std;int main(){	int i;	while(!(cin >> i))	{		cout << "boo\n";		cin.clear();  // Reset the failbit.		cin.ignore(); // Ignore the offending character.	}	cout << "yay\n";	return 0;}


Edit: Note that if you use the using namespace std; statement, you don't need to fully qualify cin with std::cin. By using the using statement, you eliminate the need to do so.

-hellz
Actually, this is better:

#include <iostream>#include <limits>using namespace std;int main(){	int i;	while(!(cin >> i))	{		cout << "boo\n";		cin.clear();  		cin.ignore(numeric_limits<int>::max(), '\n');	}	cout << "yay\n";	return 0;}


It saves the loop being repeated for each invalid character that was entered.

Hope that helps,

-hellz

This topic is closed to new replies.

Advertisement