I was making a program to search a track from a list of tracks by getting an input string from user.
我正在制作一个程序,通过从用户那里获取输入字符串来从轨道列表中搜索轨道。
#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
strstr()返回0
int main()
{
char search_for[80];
printf("Search for : ");
fflush(stdin);
fgets(search_for, 80, stdin);
find_track(search_for);
return 0 ;
}
1 个解决方案
#1
2
Please note that fgets
includes any trailing newline
that was part of the entry. It can be removed like this
请注意,fgets包括作为条目一部分的任何尾随换行符。它可以像这样删除
search_for [ strcspn(search_for, "\r\n") ] = 0; // remove trailing newline etc
otherwise you won't find a match.
否则你找不到匹配。
Note that fflush(stdin);
is non-standard. Note too that the scanf
given in one of the linked answers stops at the first whitespace, unless you use certain formatting to prevent it.
注意fflush(stdin);是非标准的。另请注意,其中一个链接答案中给出的scanf在第一个空格处停止,除非您使用某些格式来阻止它。
#1
2
Please note that fgets
includes any trailing newline
that was part of the entry. It can be removed like this
请注意,fgets包括作为条目一部分的任何尾随换行符。它可以像这样删除
search_for [ strcspn(search_for, "\r\n") ] = 0; // remove trailing newline etc
otherwise you won't find a match.
否则你找不到匹配。
Note that fflush(stdin);
is non-standard. Note too that the scanf
given in one of the linked answers stops at the first whitespace, unless you use certain formatting to prevent it.
注意fflush(stdin);是非标准的。另请注意,其中一个链接答案中给出的scanf在第一个空格处停止,除非您使用某些格式来阻止它。