iostream cin in a loop

Hi guys,

I'm quite confused as to why this is happening first when I enter a letter instead of a number the else statement gets executed as expected and fail gets printed out and then for some reason I am pretty much prompted to enter a nother character in without the cout printing to the console and even if enter a number it just skips to a new line and waits for more input

what is going wrong here?

thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  int main()
{
    bool worked = false;
    int number;

    while(!worked){

        cout << "enter a number" << endl;
        if(cin >> number){

            cout << "success" << endl;
            worked = true;
        }else{

            cout << "fail" << endl;
            cin.clear();
            cin.ignore(1000,'/n');
        }
    }
}


edit ** should have been \n not /n sorry guys
Last edited on
It's all about that /n vs. \n. With /n, you're telling cin.ignore() to ignore input until you get a character whose value is 12142, or until you read 1000 characters. Since no character has that value, it just keeps ignoring. If you keep on typing to give it 1000 characters, you'll get some output again.

Change /n to \n on line 17 and it will work.
you get a character whose value is 12142

I never knew that. That's because it treats it as hex literal of sorts? e.g. '/n' -> {47|110} -> {2F|6E} -> 0x2F6E = 12142? Seems like a great way to obfuscate code and introduce bugs...
Last edited on
It's a multicharacter literal - it has type int.

Its value is implementation-defined, but IIRC most implementations use them to build integers byte-by-byte.
To find complete solution about iostream cin in a loop, Traininginlucknow is the best place for you.
Thanks & Regards
Last edited on
Topic archived. No new replies allowed.