Jump to content
  • Advertisement
Sign in to follow this  
J2902

While Loops

This topic is 3716 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!