简体   繁体   中英

Strcmp not working, even when comparing the same character

![在此处输入图片说明 在此处输入图片说明 在此处输入图片说明 I'm baffled. I'm working on a project that requires the use of strcmp and it doesn't seem to be working at all. Above you see an example in gdb where two characters are said to be unequal. Obviously similar results when I compare my two char arrays. Further, when I compare the arrays with themselves I also get false (name above is a char[8]). When I run strcmp within my code on the same array it produces the correct results but not in gdb (seen in the third image) I just need a lead on where to look/what to do.

Thanks.

edit: the two code fragments from the images:

print strcmp("S", "S")==0
print strcmp(name, name)==0

You're using the wrong set of quotes.

The strcmp function expects both arguments to be of type const char * , ie a pointer to a null terminated string. In C++ (and C) single quotes are used for single characters, while double quotes are used for null terminated strings. So you're not passing arguments of the proper type.

The proper way to do this comparison is:

strcmp("S", "S") == 0

When the strings are equal strcmp returns 0 , false , I think you are expecting 1 , true. But that's how it is. You can wrap it in your own function and your function can return true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM