Character array comparison

I have a 2D char array called Choice[10]. My code is,

char Choice[10]

1
2
3
4
5
6
7
8
9
10
11
cin.getline( Choice, 10 );

	if(Choice, "Attack")
	{
		Attack();
		Grunt.Health = Grunt.Health-Damage; //Applying Damage
	}
	else if(Choice, "Flee")
	{
		Run();
	}


Why is it, my code always goes to Attack, and never goes to Flee, even if I enter Flee?
your using a comma. Use strcmp() and check if it returns 0;
1
2
3
4
5
6
7
8
if ( strcmp(Choice, "Attack") == 0 )
{
//code
}
else if ( strcmp(Choice, "Flee") == 0)
{
//more code
}
strcmp smells a lot like C, this is C++, std::strings like most types I can think of in C++ can be compared with their overloaded operator == like this

if ( Choice == "Attack" )
strcmp works perfectly! Thanks. I tried using == to test between the two, and that results in the program considering neither to be true. Hm, someone in the past had told me to use commas in the case of comparing 2D character arrays. Thanks though, for clearing it up!
std::string can be compared with ==, but getline returns a char*, not a std::string.
Cheers Moschops, you live and learn
@quirky: I was originally going to suggest the == for std::string but I saw that he was using a char array and since this is just a snippet of code I didn't know whether I was worth to make him rewrite whatever he had done. Personally I still recommend when you can switching your char arrays over to std::strings which work better and are easier to use.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

int main() {
    std::string Choice;
    std::cin >> Choice;
    if ("Attack" == Choice) {
        // do somthing here
    } else
        if ("Flee" == Choice) {
            // do something else here
        }
    return 0;
}
mp121209, that will cause problems if it is in a loop. The second time it will get a "\n" rather than the next line. That is because there is a more-or-less 1 to 1 correspondence between cin >> and scanf, and >> (string) corresponds to scanf("%s"), which gets a string of non-whitespace characters, a 'word'. Better to use getline.
Using strcmp() is correct.
Another option is to cast to a std::string() in your comparison:

1
2
3
4
char* a = "Hello";
char b[] = "world";

if (string( a ) == b) ...
Topic archived. No new replies allowed.