Why isn't this working ? -Help-

Hello i'm stuck on something in my code most of it has been removed so i dont really want people taking my idea ( sorry might seem sad but still )

my problem is from the first if everything works on the inside of that but the else if and the end of the first one and the code doesn't work even if i write the things to trigger it, it just assumes its "yes";

http://puu.sh/3zYoC.png heres a picture of the problem
i typed no but it still continues why isn't it saying " the monster got away " ?

attackAnswer is string not a char so this should work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
       
       string attackAnswer = "";

    	if ( attackAnswer == "Yes" || "yes" || "y" || "Y" )
	{
		
		
		if ( chosenClass == 1)
		{

			if ( spellChoice == 1)
			{
			}

			else if ( spellChoice == 2)
			{
			}
		}

		else if( chosenClass == 2)
		{
			
			
			if ( spellChoice == 1)
			{
			}

			else if ( spellChoice == 2)
			{
			}
	   }
	}

	else if ( attackAnswer == "No" || "no" || "n" || "N" )
	{
		cout << " monster ran away " << endl;
	}
 


could someone possibly help me to why this is happening i've only been learning c++ a while now and yes i know its a lot of nested else if statements but i dont know how to really do it yet/

Thanks so much :)
Last edited on
You need to put "attackAnswer ==" between the comparisons:
 
if ( attackAnswer == "Yes" || attackAnswer == "yes" || attackAnswer == "Y" || attackAnswer == "y" )


Same with line 34, and any other time you want to do multiple conditions.

Otherwise: "yes" is a const char* with a value that is not zero ( so its true ).
Last edited on
if( attackAnswer == "Yes" || "yes" || "y" || "Y" )
This isn't doing what you think it is doing. The only conditional check is the first clause; the rest are all separate, meaning that attackAnswer has nothing to do with them. This line will always evaluate to true.

You must write out attackAnswer for every condition you want to check for:
if( attackAnswer == "Yes" || attackAnswer == "yes" || ... )
It is probably best not to try and accommodate every combination of the words "Yes" and "No". You will just be writing unnecessarily complex code.

Make attackAnswer a char, then make use of the toupper or tolower functions and do a comparison involving 'Y'

You could also make use of the ternary operator, which is a short cut for the if-then-else construct, which would allow you to do these on 1 LOC. Have a read of this article by chrisname :

http://www.cplusplus.com/forum/articles/14631/


You could make use of functions calls, so if it's true call a function, otherwise call a different function.

Only make things complex if they need to be, otherwise keep it simple.

Einstein wrote:
Things should be simple, simple as possible, but no simpler


Hope all goes well
Topic archived. No new replies allowed.