当我试图在codeblocks编译器中运行此程序时,strstr()函数每次都返回0。为什么?
我正在制作一个程序,通过从用户处获取输入字符串,从曲目列表中搜索曲目当我试图在codeblocks编译器中运行此程序时,strstr()函数每次都返回0。为什么?,c,string,codeblocks,strstr,C,String,Codeblocks,Strstr,我正在制作一个程序,通过从用户处获取输入字符串,从曲目列表中搜索曲目 #include<stdio.h> #include<string.h> char tracks[][80] = { "I left my heart in harvard med school", "Newark, newark - a wonderful town",
#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++)
{
strstr()返回0
请注意,
fgets
包括作为条目一部分的任何尾随换行符。它可以像这样被移除
search_for [ strcspn(search_for, "\r\n") ] = 0; // remove trailing newline etc
否则你就找不到匹配的
注意fflush(stdin)代码>是非标准的。还请注意,其中一个链接答案中给出的scanf
会在第一个空格处停止,除非您使用某些格式来阻止它。它的副本在search\u for
中包含一个换行符。此程序正在运行。但是我想知道为什么我不应该使用fflush(stdin)
?fflush(stdin)
不是标准C实现的一部分,但它是在MSVC和其他实现中定义的。所以它不可移植。我发布了一个新问题。当我进行研究时,我发现使用fflush(stdin)
将帮助我解决问题。我应该使用它还是搜索其他解决方案?只有在编译器手册中记录了它并且您愿意编写不可移植代码时才使用它。
int main()
{
char search_for[80];
printf("Search for : ");
fflush(stdin);
fgets(search_for, 80, stdin);
find_track(search_for);
return 0 ;
}
search_for [ strcspn(search_for, "\r\n") ] = 0; // remove trailing newline etc