Why does this particular piece of code return false on the strstr() if I input "test"?
char input[100];
int main()
{
fgets(input, 100, stdin);
printf("%s", input);
if(strstr("test message", input))
{
printf("strstr true");
}
}
I thought strstr searched the first param for instances of the second param? It works when I replace input with some text or just assign it something directly, but it seems to not work with fgets.
It's because fgets stores the newline character so when strstr does a comparison it fails.
From the man page:
Add
input[strlen(input) - 1] = '\0';
after thefgets
.fgets
reads in the newline char ('\n'
). There is no'\n'
in"test message"
soinput
will never be contained within it.You should really check to see if the newline is at the end of the buffer after calling
fgets
to know if the whole line was able to actually fit into it, and also to obviously remove it.