using || in do-while loop

I have this program here, it isn't complete, just starting it off. It's a switch sequence within a do while loop. If the user input is Q or q the program should quit. However when I put while((option != 'Q') || (option != 'q')); It doesn't end the program either way but if I just put while(option != 'Q'); it ends when i type in Q but I also need it to end when I type in q. Here 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
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

int main()
{
	char choice;
	do
	{
	cout << "[P]osition, [R]everse, [A]verage, [S]earch, [Q]uit " << endl
		<< "Please select an option: ";
		cin >> choice;

		switch (choice)
		{
		case 'P':
		case 'p':
			cout << "test";
			break;

		case 'R':
		case 'r':

		case 'A':
		case 'a':

		case 'S':
		case 's':
			break;
		}
	} while ((choice != 'Q') || (choice != 'q'));


	system("Pause");
	return 0;
}
Last edited on
You have to use &&, not ||.

Alternately, you can also just say: while ( toupper(option) != 'Q' ) ;
It helps to refer to truth tables.

Truth table for logical or:
  A    B   | A || B
-----------+-------
  T    T   |   T
  T    F   |   T
  F    T   |   T
  F    F   |   F


When either condition is true, the overall condition is true. If choice is 'Q' then choice != 'q' is true. Likewise, if choice is 'q', then choice != 'Q' is true. And if neither is the case, the overall expression also evaluates to true, so what you wrote is equivalent to:
1
2
3
  do {
    ...
  } while (true);
Here, given the way you are using the switch statement, you could do this instead:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
using namespace std;

int main()
{
    bool is_running = true;
    
    do
    {
        cout << "[P]osition, [R]everse, [A]verage, [S]earch, [Q]uit " << endl
        << "Please select an option: ";
        char choice = '\0';
        cin >> choice;

        switch (choice)
        {
        case 'P':
        case 'p':
            cout << "test\n";
            break;

        case 'R':
        case 'r':
            break;
            
        case 'A':
        case 'a':
            break;

        case 'S':
        case 's':
            break
            
        case 'Q':
        case 'q':
            is_running = false;
            break;            
        }
    } while (is_running);

    system("Pause");
    return 0;
}
Last edited on
Topic archived. No new replies allowed.