loop in switch

I wanted to have the loop closing when value x is 1, 2 or 3, it works if i write only x!=1 but with or operator i can't manage to make it work, thanks in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main (){
    int x;
    while((x!=1)||(x!=2)||(x!=3)){
        cin >> x;
        switch(x){
        case 1: cout << "one is one" << endl;
        break;
        case 2: cout << "two is two" << endl;
        break;
        case 3: cout << "three is three" << endl;
        break;
        default: cout << x << " is not 1, 2 or 3" << endl;
        break;
    }
}
}
Line 7: You want the && operator, not the || operator.

BTW, the first time through the loop you're going to be comparing garbage because x is not initialized. Your condition may or may not work depending onb the value of the garbage.

Last edited on
you need to initialise x on line 6.

just to add what AA said, you could do something like this:

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
#include <iostream>

using namespace std;

int main(){
	int x(0);
	bool done(false);

	while (((x != 1) || (x != 2) || (x != 3)) != done)
	{
		cin >> x;
		switch (x){
		case 1: cout << "one is one" << endl;
			break;
		case 2: cout << "two is two" << endl;
			break;
		case 3: cout << "three is three" << endl;
			break;
		default: cout << x << " is not 1, 2 or 3" << endl;
			done = true;
			break;
		}
	}
}

but using && is cleaner.

That's assuming when you said "I wanted to have the loop closing" i understood that as you want the loop finishing?
Last edited on
thanks
Topic archived. No new replies allowed.