Sign in to follow this  
Aniviel

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

Recommended Posts

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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this