limiting input in console.

Hi. I am writing a mastermind console game. Everything is working except for the fact that I can not limit input. eg:

1
2
3
 
cin << x0 << x1 << x2 << x3;
// blah blah blah. 


my problem is, that when i type more than for characters, the remaining characters are stored in the buffer and get execute by the comparison code simultaneously after each other.
lets say the max input is 4 chars.
and each turn the number of chars in the correct chars in the correct place and the number of correct chars in the wrong place is returned.

so writing 12345
will result in: 3 in correct place, 0 in wrong place
0 in correct place, 1 in wrong place

regardless of the values.

How do i solve this?
While the syntax cin >> var1 >> var2 >> var3 ... is simple and elegant, its lack of error handling makes it almost useless for any non-trivial application.

I suggest reading a line of text and parsing it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
while( true ) {
    cout << "What is your guess? " << flush;
    string line;
    getline( cin, line );

    if( line.length() > 4 ) {
        cerr << "Invalid input: too many characters entered." << endl;
        continue;
    }

    if( line.length() < 4 ) {
        cerr << "Invalid input: not enough characters entered." << endl;
        continue;
    }

    // ... Make sure each character line[0], line[1], line[2], line[3] are valid
    if( /* One or more characters invalid */ ) {
        cerr << "Invalid input: one or more characters are invalid." << endl;
        continue;
    }

    // Otherwise process (outside loop)
    break;
}

Topic archived. No new replies allowed.