I have been looking around the internet all day looking for a way to stop my program from entering an infinite loop when the user enters anything except a number when I cin an int.

For example:

while(blah blah)
{
    int x;
    cin >> x;

    if(x == 4)
    break;
}

If the user enters anything but a number, the loop will never exit and it will never ask the user to input another number. I've tried using static_cast but that doesn't work either. I am at a complete loss as to what to do. I am using Visual Studio 2010 if that matters.

Recommended Answers

All 3 Replies

So as soon as I posted this I think I found my answer. I just had to use cin.clear() to let the user input another number. This always happens to me... I am still testing to see if it is actually fixed, I'll close the thread in a couple minutes if that was the answer.

>> I am using Visual Studio 2010 if that matters.

I don't think it matters. This is a C++ issue. If you try to read "z" into an int, cin just keeps trying and it will never get that int. You need to reset it to a good state and get that pesky "a" or whatever else is clogging things up and try again.

while(1)
    {
        int x;
        cout << "Enter 4 : ";
        cin >> x;
        if(!cin.good())
        {
            // get rid of the stream and make it good, then scold the user.
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Not only did you not enter 4, you didn't even enter an integer.\n";
            continue;
        }
		
        if(x == 4)
        {
            cout << "Good.  You may leave the loop.\n";
            break;
        }
        else
        {
            cout << "That's a number, but it isn't 4.\n";
        }
    }

Thanks for the reply but the simple cin.clear() works. From what I read it just resets the fail flag in cin. Now to figure out how to wait for user input without using _getch()...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.