Question:
why strcmp fails in my c++ program?
?
2012-02-29 08:43:09 UTC
My program is compiled by VC++ 2008. It seems failed to compare sometimes.
I get some log messages "Unknown action yyy".

const char *reqType = ...;
if (reqType) {
if (strcmp(reqType, "xxx") == 0) {
...
} else if (strcmp(reqType, "yyy") == 0) {
...
} else {
printf("Unknown action %s\n", reqType);
}
}
Four answers:
peteams
2012-02-29 09:35:54 UTC
The test strcmp(reqType, "yyy") == 0 will be false if reqType is not exactly "yyy". If one or more of the y-characters is uppercase it will fail, additionally if there are spaces or other non-printing characters before, after or in between the y-characters the test will fail.



If you're doing pointer stuff elsewhere in the application, C++ being C++, the test can also fail if the constant "yyy" gets trampled in memory or (less likely) the actual program code gets trampled.
justme
2012-02-29 09:15:38 UTC
because reqType is just a pointer to a char and has no value assigned to it.



Not sure what this is:

const char *reqType = ...; the three dots, but it isnt assigning anything to the pointer.
ahmed
2016-12-08 21:45:10 UTC
How is the string terminated? Your compiler ought to null terminate the string "go out" for you. So notably much no concerns there. Is the different string null terminated? in maximum circumstances it is only a nil or NULL whether it relatively is non-0. while you're no longer terminating them then who's? In C, no longer a lot is accomplished for you. With strings, you desire to be very careful approximately terminating them exact. most of the library applications assume null terminators and that they ought to be there. additionally, you ought to to place in writing a sprint print function with limits that reflects the strings you're comparing. even have the little print function show any detected null terminator. perhaps you're no longer comparing what you think of you're. Shadow Wolf
James Bond
2012-02-29 08:48:15 UTC
reqType is a string.

You can not use string in if condition

if(reqType) check


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...