Ignore all input after the first char

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
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
But then you have an entire string object in memory. Just use cin.sync()

1
2
cin >> ansPlay;
cin.sync();
Last edited on
Thanks omeraslam and LowestOne for responding. LowestOne, I used your suggestion and it worked, thank you very much.
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.