what am i missing

So i am new to programming. I am having some trouble writing a do while loop that will stop the code when i type in exit or EXIT. The code below is a shorter version of my actual code and doesn't have the nested conditions but functions the same.

My issue is: When i type in "exit" or "EXIT" my program seems to be entering the if statements and wants to put out the else condition and then loops again.

any help would be greatly apprecticed

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{

cout << setprecision (2) <<fixed <<endl;

string var;


do
{
cout <<"This store sells notebooks , pencils, and pens.\n";
cout <<"Type NOTEBOOK, PENCIL, PEN, or EXIT: ";
cin >>var;

if(var != "exit" || var != "EXIT")
{
if(var == "NOTEBOOK" || var == "notebook")
cout <<"notebook\n\n";
else if(var == "PENCIL" || var == "pencil")
cout <<"pencil\n\n";
else if(var == "PEN" || var == "pen")
cout <<"pen\n\n";
else
{
cout <<"Srry we dont not sell that\n";
}
}
}while (var != "EXIT" || var != "exit");

system("pause");
return 0;
}
Bad logic. if (var != "exit" || var != "EXIT") is always true, because it's always not equal to either one or the other. You should change all of your logical OR || statements with != in them to logical AND && statements.

EDIT: Clarifying.
Last edited on
Consider how || (OR) works. If one of the statements is true, then the entire if statement is true and the if block will be entered.

So let's consider:

if(var != "exit" || var != "EXIT")

What happens if I type in "exit"?

1
2
3
      false          true
if(var != "exit" || var != "EXIT")
 

One of the statements is true, so the entire thing is true, so we enter the if block.

Similarly, if I type in "EXIT":

1
2
3
      true          false
if(var != "exit" || var != "EXIT")
 


we'll also enter the if block!

You probably want to check to make sure var doesn't equal exit AND (&&) var doesn't equal EXIT.
that worked!!!
thanks so much guys, i know i have changes my logic before, however i did not change all of the or (||) to and (&&) in the same instance.

failures are the best learning mechanism :-D
Topic archived. No new replies allowed.