当我试图在代码块编译器中 运行 这个程序时,strstr() 函数每次都返回 0。为什么?
When I was trying to run this program in the codeblocks compiler, the strstr() function was returning 0 everytime. Why?
我正在制作一个程序,通过从用户那里获取输入字符串来从曲目列表中搜索曲目。
#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++)
{
the control reaches upto this line of code
m = strstr(tracks[i], search_for);
if(m)
{
printf("Track%i : '%s' \n", i, tracks[i]);
}
}
}
strstr() returns 0
int main()
{
char search_for[80];
printf("Search for : ");
fflush(stdin);
fgets(search_for, 80, stdin);
find_track(search_for);
return 0 ;
}
请注意 fgets
包括作为条目一部分的任何尾随 newline
。可以这样去掉
search_for [ strcspn(search_for, "\r\n") ] = 0; // remove trailing newline etc
否则找不到匹配项。
请注意 fflush(stdin);
是非标准的。另请注意,其中一个链接答案中给出的 scanf
会在第一个空格处停止,除非您使用某些格式来阻止它。
我正在制作一个程序,通过从用户那里获取输入字符串来从曲目列表中搜索曲目。
#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++)
{
the control reaches upto this line of code
m = strstr(tracks[i], search_for);
if(m)
{
printf("Track%i : '%s' \n", i, tracks[i]);
}
}
}
strstr() returns 0
int main()
{
char search_for[80];
printf("Search for : ");
fflush(stdin);
fgets(search_for, 80, stdin);
find_track(search_for);
return 0 ;
}
请注意 fgets
包括作为条目一部分的任何尾随 newline
。可以这样去掉
search_for [ strcspn(search_for, "\r\n") ] = 0; // remove trailing newline etc
否则找不到匹配项。
请注意 fflush(stdin);
是非标准的。另请注意,其中一个链接答案中给出的 scanf
会在第一个空格处停止,除非您使用某些格式来阻止它。