tags:

views:

107

answers:

3

Major brainfreeze while learning C here.

I have a struct here with something like:

char *sname;
........
players[i].sname

equalling "James".

I need to check for equality between values like so:

if (players[i].sname == 'Lee')

but am not having much luck. Is there a str function I should be using or is there anyway to fix up my if statement. It's not working atm.

+8  A: 

You should be using strcmp():

if (strcmp(players[i].sname, "Lee") == 0) { ...

Also note that strings in C are surrounded by double quotes: "". Single characters are surrounded by single quotes: ''. I'm not sure exactly what your compiler might be doing with 'Lee', but it's almost certainly not what you want.

Greg Hewgill
The compiler will probably generate the number `0x004c6565`. I'm not sure if multibyte characters were legal in C89, but I'm pretty sure they're part of C99.
Chris Lutz
+3  A: 

You'd be looking for strcmp() from the header <string.h>.

Jonathan Leffler
+7  A: 

The short answer: strcmp().

The long answer: So you've got this:

if(players[i].sname == 'Lee')

This is wrong in several respects. First, single-quotes mean "character literal" not "string literal" in C.

Secondly, and more importantly, "string1" == "string2" doesn't compare strings, it compares char *s, or pointers to characters. It will tell you if two strings are stored in the same memory location. That would mean they're equal, but a false result wouldn't mean they're inequal.

strcmp() will basically go through and compare each character in the strings, stopping at the first character that isn't equal, and returning the difference between the two characters (which is why you have to say strcmp() == 0 or !strcmp() for equality).

Note also the functions strncmp() and memcmp(), which are similar to strcmp() but are safer.

Chris Lutz
Thank you so much - I knew there was something fundamentally wrong. When you don't know which part is wrong from many parts, it's hard to actually look it up :P
Dominic Bou-Samra