Having a little problem with cin and a while loop.

I'm having a problem with this code.
1
2
3
4
5
6
7
8
9
10
11
12
13
    int nX;
    while (1)
    {
        cin >> nX;
        if (nX == 1)
            break;
        else if (nX == 2)
            break;
        else if (nX == 3)
            break;
        else
            cout << "Please enter a valid answer: " << endl;
    }


If I enter any number other than 1 2 or 3 the program outputs
4
Please enter a valid answer:

until I pick a number 1-3.

If I enter letters though it outputs
c
Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer:

endlessly

I'm not sure why it's doing this isn't 'c' supposed to evaluate to 99?

also why is "c" == 4644900?

EDIT: I think 4644900 might be a pointer but I'm not sure can someone confirm this?
Last edited on
When you input 'c', cin will go into an error state because it was expecting a number. You have to clear out the junk yourself then .clear() cin to clear the error state.
When you enter a character when cin is supposed to stream input to an int, cin sets a fail flag. Once that happens, no calls to "cin >>" will occur until the flags are reset.
So after displaying "Please enter a valid answer: ", the loop goes to line 5, which is skipped over because one of the fail flags is set. This leaves nX unchanged, so the else statement is executed again.

To clear/reset the flags:
 
cin.clear();
you should also use cin.ignore after clearing the buffer.

1
2
3
std::cin.ignore( std::numeric_limits<streamsize>::max() , '\n' ); //#include <limits>
//or
std::cin.ignore( 1024 , '\n' ); //any decent size number I suppose 
@Momoironeko

I think you would be better off with a switch statement inside a while loop. Have a default case to handle bad input, and a quit case. The while loop is controlled by a boolean variable.

Have a look at this :

http://www.cplusplus.com/forum/beginner/104553/2/#msg564228


Hope all goes well.
Thanks I used a little of all of your responses.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int nX;
bool btrue = false;

    while (!btrue)
    {
        switch(nX)
        {
            case 1 :
                btrue = true;
                break;

            case 2 :
                btrue = true;
                break;

            case 3 :
                btrue = true;
                break;

            default :
                std::cin.clear();
                std::cin.ignore( 100 , '\n' );
                std::cout << "Please enter a number 1 to 3: ";
        }
     }
Topic archived. No new replies allowed.