I'm trying to compare a string using strcmp(), but when I'm trying to compare a formatted string, it won't work, e.g:
if(strcmp(buffer, ("Number %d", 4)) == 0)
{
// do stuff
}
How do I compare formatted strings in C?
The notation ("Number %d", 4)
inside an argument list to a function is a comma operator separating two expressions, the first of which ("Number %d"
) is evaluated (for its side-effects — only there are no side-effects so a good compiler might warn about that) and the result discarded, and the second of which is evaluated and passed as the argument to the function — strcmp()
.
The compiler should be complaining about a type mismatch for argument 2 of strcmp()
; the 4
is not a string that can be passed to strcmp()
. If your compiler is not complaining, you need to find out how to make it complain.
This would work:
char formatted[32];
snprintf(formatted, sizeof(formatted), "Number %d", 4);
if (strcmp(buffer, formatted)) == 0)
{
/* do stuff */
}