Jump to content
  • Advertisement
Sign in to follow this  
Aniviel

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

This topic is 5148 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!