I'm confused on how to do OR while do Boolean. "||" that won't work for me for some reason

110 views Asked by At

here is my code. I want my if statement to work if the user types in Yes or yes. When I take out || and the "yes" My program works fine and when the user types in "Yes" it works. I wanted to make my program better and also have it so that when they type in "yes" to work. Can someone help me figure this out? Thanks!

{

    cout<<"Would you like to begin?\n";


    cin>>answer;

    if (answer=="Yes" || "yes") {

        continue_1=true;

        google=false;

    }

    else {

        if (answer=="No" || "no" ) {

            cout <<endl<< "have a nice day\n";

            google= false;

            return 0;

        }
5

There are 5 answers

0
Tim B On

You are doing the or on the strings, not on the query - you want:

    if (answer=="No" || answer=="no" ) {

To be more generic about it though you could convert the string to lowercase and then compare that with "no", which will handle "No", "NO" and "no" for you.

Quite a common alternative approach is to just check that the first character in the string is either N or n. That also picks up things like Nope, etc.

2
Josh Engelsma On
if (answer=="Yes" ||  answer == "yes")

You need to use the == in both checks. Unfortunately it doesn't work otherwise

0
Simon McLoughlin On

The correct syntax is:

if (answer=="Yes" || answer=="yes")

It doesn't carry anything from the first side, OR's and AND's can be used to mix different values. like this:

if (answer=="Yes" || otherAnswer=="no")
0
Ed Heal On

Where does one start?

Precedence - see http://en.cppreference.com/w/cpp/language/operator_precedence String comparison = See http://www.cplusplus.com/reference/cstring/strcmp/

And learn about pointers

0
nurettin On

I would rather do it with less branching:

cout<<"Would you like to begin?\n";
cin>>answer;

if (answer== "No" || answer== "no")
  return 0;

if (answer!= "Yes" && answer!= "yes" )
  return error; // only answer with yes or no

// here, we know that the answer is yes