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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With