【问题标题】:When I was trying to run this program in the codeblocks compiler, the strstr() function was returning 0 everytime. Why?当我试图在代码块编译器中运行这个程序时,strstr() 函数每次都返回 0。为什么?
【发布时间】:2016-10-20 01:18:22
【问题描述】:

我正在制作一个程序,通过从用户那里获取输入字符串来从曲目列表中搜索曲目。

#include<stdio.h> 
#include<string.h>

char tracks[][80] = {
                        "I left my heart in harvard med school",
                        "Newark, newark - a wonderful town",
                        "Dancing with a dork",
                        "From here to maternity",
                        "The girl from Iwo Jima",
};

void find_track(char search_for[])
{
    int i, m = 0;
    for(i = 0; i<5; i++)
    {

控件到达这行代码

        m = strstr(tracks[i], search_for);     
        if(m)
        {
            printf("Track%i : '%s' \n", i, tracks[i]);
        }
    }
}

strstr() 返回 0

int main()
{
    char search_for[80];
    printf("Search for : ");
    fflush(stdin);
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0 ;

}

【问题讨论】:

标签: c string codeblocks strstr


【解决方案1】:

请注意,fgets 包括作为条目一部分的任何尾随 newline。可以这样去掉

search_for [ strcspn(search_for, "\r\n") ] = 0;   // remove trailing newline etc

否则你将找不到匹配项。

请注意,fflush(stdin); 是非标准的。另请注意,其中一个链接答案中给出的 scanf 在第一个空格处停止,除非您使用某些格式来防止它。

【讨论】:

  • 这个程序正在运行。但我想知道为什么我不应该使用fflush(stdin)
  • fflush(stdin); 不是标准 C 实现的一部分,但它在 MSVC 和其他实现中定义。所以它不是便携式的。
  • 我发布了一个新问题。当我研究时,我发现使用fflush(stdin) 会帮助我。我应该使用它还是寻找替代解决方案?
  • 只有在你的编译器手册中记录了它并且你愿意编写不可移植的代码时才使用它。
猜你喜欢
  • 2019-08-07
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
相关资源
最近更新 更多