strstr 不起作用 [英] strstr not functioning

查看:40
本文介绍了strstr 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我输入test",为什么这段特定的代码会在 strstr() 上返回 false?

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");

    }


}

我以为 strstr 在第一个参数中搜索了第二个参数的实例?当我用一些文本替换输入或直接为其分配一些东西时它会起作用,但它似乎不适用于 fgets.

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.

推荐答案

这是因为 fgets 存储了换行符,所以当 strstr 进行比较时它会失败.

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

来自手册页:

fgets() 从流中读入至多小于 size 个字符并将它们存储到 s 指向的缓冲区中.阅读停止后EOF 或换行符.如果读取换行符,则将其存储进入缓冲区.'' 存储在缓冲区中的最后一个字符之后.

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.

这篇关于strstr 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆