简体   繁体   English

strstr不起作用

[英]strstr not functioning

Why does this particular piece of code return false on the strstr() if I input "test"? 如果我输入“test”,为什么这段特殊的代码在strstr()上返回false?

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? 我以为strstr在第一个参数中搜索了第二个参数的实例? It works when I replace input with some text or just assign it something directly, but it seems to not work with fgets. 当我用一些文本替换输入或直接分配它时,它可以工作,但它似乎不适用于fgets。

It's because fgets stores the newline character so when strstr does a comparison it fails. 这是因为fgets存储换行符,所以当strstr进行比较时失败。

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. fgets()从流中读取最多一个小于大小的字符,并将它们存储到s指向的缓冲区中。 Reading stops after an EOF or a newline. 读数在EOF或换行符后停止。 If a newline is read, it is stored into the buffer. 如果读取换行符,则将其存储到缓冲区中。 A '\\0' is stored after the last character in the buffer. 在缓冲区中的最后一个字符之后存储'\\ 0'。

Add input[strlen(input) - 1] = '\\0'; 添加input[strlen(input) - 1] = '\\0'; after the fgets . fgets fgets reads in the newline char ( '\\n' ). fgets读取换行符char( '\\n' )。 There is no '\\n' in "test message" so input will never be contained within it. "test message"没有'\\n' ,因此input将永远不会包含在其中。

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. 你应该在调用fgets之后检查新行是否在缓冲区的末尾,以确定整行是否能够真正适合它,并且显然也要删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM