Ignore all input after the first char

May 31, 2012 at 4:15pm
This is my code:
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
26
27
int main()
{
    char ansPlay;
    cout<<"Welcome! Would you like to play a game of Roulette? \n<Y>es or <N>o"<<endl;
    while(1)
    {
        cin>>ansPlay;
        
        if(ansPlay == 'N' || ansPlay == 'n')
        {
            cout<<"Too bad. See you next time.";
            cin.get();
            return 0;
        }
        else if(ansPlay == 'Y' || ansPlay == 'y')
        {
            cout<<"Wonderful! Let's Play!";
            break;
        }
        else
        {
            cout<<"The answer needs to be <Y>es or <N>o. Try again."<<endl;
        }
    }
    cin.get();
    return 0;
}

Now, when I give "yes" or "no" or anything starting with an "n" or a "y" it works just fine. But if I enter for example: "asdf", it gives the output: "The answer needs to be <Y>es or <N>o. Try again." four times, once for every character. So I was wondering if there's a way to discard all characters that come after the first? Or if this is not the right way to do it, how should it be done?
Thanks in advance.
Last edited on May 31, 2012 at 4:16pm
May 31, 2012 at 4:37pm
instead of char ansPlay use string ansPlay and use ansPlay[0] == 'Y' in if conditions.
include string header file if it gives error
Last edited on May 31, 2012 at 4:39pm
May 31, 2012 at 4:59pm
But then you have an entire string object in memory. Just use cin.sync()

1
2
cin >> ansPlay;
cin.sync();
Last edited on May 31, 2012 at 5:00pm
May 31, 2012 at 5:17pm
Thanks omeraslam and LowestOne for responding. LowestOne, I used your suggestion and it worked, thank you very much.
May 31, 2012 at 5:43pm
Note that cin.sync() work different on different compilers.

Isn't it enough to discard all input until the end of the line? You can do that by using ignore:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Topic archived. No new replies allowed.