stuck in this loop?

I have this function but no matter what the user enters it says invalid input. Any suggestions?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char GetChoice(char selection)
{
         cin >> selection;

	while (selection != 'y' || selection != 'n' || !cin)
	{
		cin.ignore(200, '\n');
		cin.clear();
		cout << "Invalid input. Please try again: ";
		cin >> selection;
	}
	
        if (selection == 'y')
                cout << "Awesome!";

        else if (selection == 'n')
                 cout << "I'm sorry.";

	return selection;
}
Last edited on
Think about...
selection != 'y' || selection != 'n'

Will it ever be false?
Wouldn't it be false if the user input a 'y' or 'n'?
So...
selection is 'y'.

selection != 'y' || selection != 'n' || !cin
gets translated to:
0 || 1 || 0
Which becomes
1

selection is 'n'.

selection != 'y' || selection != 'n' || !cin
gets translated to:
1 || 0 || 0
Which becomes
1

selection is 'x'.

selection != 'y' || selection != 'n' || !cin
gets translated to:
1 || 1 || 0
Which becomes
1

What you need is &&.

(selection != 'y' && selection != 'n') || !cin

Which is translated, in order:
(0 && 1) || 0 ( -> 0, correct )
(1 && 0) || 0 ( -> 0, correct )
(1 && 1) || 0 ( -> 1, correct )

EDIT:
You may also want to change it with this:

1
2
3
4
5
6
7
8
9
10
11
12
char GetChoice()
{
    char selection=0;
    while(!(cin >> selection))
    {
        if(selection == 'y' || selection == 'n')
            break;
    }
    if(!(selection == 'y' || selection == 'n')) // if cin failed...
        return 0; // return 0
    return selection; // or return 'y' or 'n'.
}
Last edited on
Topic archived. No new replies allowed.