c/c++语言开发共享strstr()函数

我正在尝试编写一个程序,将用户输入的子字符串与字符串数组进行比较。

#include  #include  char animals[][20] = { "dogs are cool", "frogs are freaky", "monkeys are crazy" }; int main() { char input[10]; puts("Enter animal name: "); fgets(input, sizeof(input), stdin); int i; for(i = 0; i < 3; i++) { if(strstr(animals[i], input)) printf("%s", animals[i]); } return 0; } 

当我进入青蛙时,例如它应该打印出“青蛙怪异”的信息,但它没有打印出来。

所以我试着写一行来每次打印出strstr()函数的值,它们都返回0,这意味着所有的比较都失败了。 我不明白为什么,有人能帮帮我吗?

    这是因为您的字符串包含换行符。

    来自fgets文档 :

    换行符使fgets停止读取,但它被函数视为有效字符,并包含在复制到str的字符串中。

    这应该解决问题( 演示 ):

     #include  #include  char animals[][20] = { "dogs are cool", "frogs are freaky", "monkeys are crazy" }; int main() { char input[10]; printf("Enter animal name: "); scanf("%9s", input); int i; for(i = 0; i < 3; i++) { if(strstr(animals[i], input)) printf("%s", animals[i]); } return 0; } 

    fgets包含缓冲区中的输入换行符。 你的字符串中没有换行符,因此它们永远不会匹配。

    最有可能的是, fgets()包括用户按Enter键时输入的换行符。 去掉它:

     char *p = strchr(input, 'n'); if (p) *p = 0; 

      以上就是c/c++开发分享strstr()函数相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560379.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐