PDA

View Full Version : weird test


EscapeCharacter
07-01-2002, 02:37 AM
any reason why this test wouldnt evaluate to true?

void MenuItem::ExecCommand(){
char *blah = this->GetCommandName();
if(blah == "Exit"){
cout << "Never getting here" << endl;
exit(0);
Exit();
}
}

assumming the GetCommandName() return "Exit". ive checked using a cout to see what the value of blah is and it IS Exit but this test always returns false, any ideas?

l01yuk
07-01-2002, 04:45 AM
I think that you should try strcmp() to compare strings.

EscapeCharacter
07-01-2002, 05:42 AM
ive tried strcmp and i get the same thing, it returns false everytime. now heres something thats really weird, when i do this:

if(blah[0] == 'E' && blah[1] == 'x' && blah[2] == 'i' && blah[3] == 't')

it works, i dont see why that would be different from the way i have it normally.

kmj
07-01-2002, 10:27 AM
Escape: strcmp returns 0 if they are the same, -1 if the first is lexicographically less than the second, or 1 if it's lexicographically greater. (I might have gotten the last two switched.) Anyway, use that.

== doesn't work because when you're comparing a char *, you're looking at the address it's pointing to, no the characters in the string. So rather than compare each element (which is comparing the character values), do strcmp. (or strncmp, or strcmpi, or strncmpi).

l01yuk
07-01-2002, 11:50 AM
Escape: Your last example works because you are comparing individual chars which are of type int.

if ('a' == 97)
{/* Print this if 97 is ASCII code for 'a' */
printf("Yes");
}
else
{
printf("No");
}

will print Yes for instance.

This example is non-portable of course though since not every platform uses the ASCII char set but that is another matter.

EscapeCharacter
07-01-2002, 12:00 PM
heh damn shoulda paid more attention to the man page thought it returned 1 on true, thanks now im finished with a big part in my program :)

strags
07-04-2002, 05:12 PM
It's worth pointing out the reason your first version didn't work.

Strings in C are char* pointers. (I'm not talking about the string class in C++).

Your == test was actually testing to see if the two char* pointers were identical - in other words if they physically pointed to the same memory location.

strcmp, on the other hand, actually runs through the letters in each string, and performs an equality check on each letter.