Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c - strstr not functioning

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because fgets stores the newline character so when strstr does a comparison it fails.

From the man page:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '' is stored after the last character in the buffer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...