The following code does not work:
char text[10];
scanf(" %s", &text);
if (strcmp(text, "some text") == 0)
puts("some text");
But when I change 'if part' thus, then everything is fine:
if (strcmp(text, "sometext") == 0)
why does it work this way and how to fix it?
The problem is not with your strcmp
call but, rather, in your scanf
call! When you type some text
as the input, scanf
will stop reading at the first whitespace, so your text
string will be "some" - and, thus, the strcmp
call will (correctly) return non-zero, as this is not the same as "some text".
For more information on this feature of scanf
, spaces and the %s
format, see this topic: How do you allow spaces to be entered using scanf?