Sign in to follow this  

While Loops

Recommended Posts

J2902    122
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

Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this