Strstr not working

Why does this particular piece of code return false in strstr () if I entered "test"?

char input[100];

int main()
{
    fgets(input, 100, stdin);
    printf("%s", input);

    if(strstr("test message", input))
    {
        printf("strstr true");

    }


}

I thought strstr was looking for the first parameter for instances of the second parameter? It works when I replace the input with some text or just assign it something directly, but it doesn't seem to work with fgets.

+5
source share
2 answers

This is because fgets saves a newline, so when strstr does a comparison, it fails.

On the man page:

fgets() , s. EOF . ,         . A '\ 0' .

+10

input[strlen(input) - 1] = '\0'; fgets. fgets char ('\n'). "test message" '\n', input .

, fgets, , , , , .

+6

All Articles