Multiple conditions in while loop for char variable.

I have a while loop whose purpose is to check if the variable letter is equal to some letters, such as in,
#include <iostream>
#include <iomanip>
using namspace std;

int main()
{
char letter;
cin>>letter;
while (letter== 'A'||'b'||'C')
{
cout<<"Test";
cin>>letter;
}
return 0;
}

I have had some issues where the while loop does not seem to recognize the || conditional operators. If I were to type in any of the approved letters, like 'A', it will not enter the loop.

What is preventing me from accessing this loop? I should point out that if I were to have the loop only test to see if the variable "letter" is equal to only 'A', it will work. It is only after inputting multiple conditional statements, that it does not work.


while(true) loop continues.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
	char letter;
	std::cin >> letter;
	while (letter == 'A' || letter == 'b' || letter == 'C')
	{
		std::cout << "Test";
		std::cin >> letter;
	}
	return 0;
}
Last edited on
If you were to change this code to,

#include <iostream>

int main()
{
char letter;
std::cin >> letter;
while ((letter != 'A') || (letter != 'b') || (letter != 'C'))
{
std::cout << "Test";
std::cin >> letter;
}
return 0;
}

So that the conditions states that if the variable "letter" is not equal to A, b, or C, it will be (true) and execute the body of the loop. However, this code here will execute the loop regardless of input (even when "letter" is 'A'). Why is that?
Last edited on
This is how to do that. I admit it is weird to think about but just step through the logic, if it evaluates to 'true' the loop is executed.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
	char letter;
	std::cin >> letter;
	while (letter != 'A' && letter != 'b' && letter != 'C')
	{
		std::cout << "Test";
		std::cin >> letter;
	}
	return 0;
}
Topic archived. No new replies allowed.