If-else-if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

int main()
{
char choice;

cout<<"(Y/N): ";
	cin>>choice;

	if (choice == 'Y'||'y'){
		cout<<"\nGlad I got that right, thanks for your help.";
	}
	else if (choice == 'N'||'n')
	{
		cout<<"You clearly dont remember your own name...";
	}
}



I cant get this to work no matter what! I tried single quotes double quotes single = and == even tried setting the "char" to "int" still to no avail. even ended up setting up the else if which at first was just an else. No matter what input I give it only tells me what it should be telling me for Y or y or the first option basically. Any help would be appreciated, I have had similar problems with this but last time it was fixed by putting a == instead of a =
You can't write an if statement like that.

1
2
3
if (choice == 'Y' || 'y') // this won't work

if (choice == 'Y' || choice == 'y') // this will! 


The same applies to all conditional statements you write.
got it ...jesus christ, searched around and it turns out that

(choice == 'Y'||choice== 'y')

is the right way to go through this.. though if someone can explain to me why id appreciate that.

EDIT:HAHA nice timing! thanks for the help pabloist, sorry for not searching a bit longer before posting
Last edited on
|| examines both sides of it. If either is true, then the result is true, otherwise the result is false.

1
2
3
4
5
6
7
8
9
10
11
12
if(true || false)
{
  // this will run
}
if(false || true)
{
  // this will run
}
if(false || false)
{
  // this will not run
}


The kicker is, in C++, ANY nonzero value is true. Since the integral value for the character 'y' is nonzero, 'y' is considered as true. So:

1
2
3
4
5
6
7
// this...
if(choice == 'Y' || 'y')

// is basically this...
if(choice == 'Y' || true)

// and since the value on the right side of the || is true, the if will always run 
Topic archived. No new replies allowed.