While Loops
Hey, I've started programming not too long ago and I've come across a problem with while loops.
Lets say I char a variable named operator. I then ask the user for input using cin (for a + or -), and I wish to use a while loop to make sure the user inputs a + or a -.
Here is a code example.
...
char operator = ' ';
...
while (operator != '+' || operator != '-')
{
// Do something...
}
...
I'm assuming the problem is in the or operator? Could anyone clarify this for me and give any known workarounds?
Thanks
The problem is that you say: while (operator != '+' || operator != '-')
which means: "While 'operator' does not equal '+' OR while 'operator' does not equal '-'"
It'll always run, because it cannot be both '+' and '-' at the same time, so one 'OR' the other, will always be 'not equal'.
You should say this: while (operator != '+' && operator != '-'), the '&&' symbol, means 'AND'.
This turns into: "While 'operator' does not equal '+' AND while 'operator' does not equal '-'"
This way, only one of those need to not be 'not equal' for the while loop to break.
which means: "While 'operator' does not equal '+' OR while 'operator' does not equal '-'"
It'll always run, because it cannot be both '+' and '-' at the same time, so one 'OR' the other, will always be 'not equal'.
You should say this: while (operator != '+' && operator != '-'), the '&&' symbol, means 'AND'.
This turns into: "While 'operator' does not equal '+' AND while 'operator' does not equal '-'"
This way, only one of those need to not be 'not equal' for the while loop to break.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement