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
std::cin and cin.fail()--infinite loops!
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!)
Try this:
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
#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:
It saves the loop being repeated for each invalid character that was entered.
Hope that helps,
-hellz
#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
Popular Topics
Advertisement