作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有下面的代码。问题是当我运行它时,它没有显示我提示的搜索;在 for 中尝试 printf("%s", strstr(tracks[i], search_for))
返回 null,但是对 tracks 做同样的事情没有问题[i] 和 search_for。请帮忙!
#include <stdio.h>
#include <string.h>
char tracks[][80]={
"I left my heart in Harvard Med Scholl",
"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;
for(i=0; i<5; i++){
if(strstr(tracks[i], search_for)){
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
};
int main(){
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
最佳答案
正如我们在 fgets()
中看到的那样文档,如果行末有换行符,它将包含在生成的字符串中:
Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.
所以在这种情况下,如果我们输入 "Newark"
,那么我们有:
search_for[] = {'N', 'e', 'w', 'a', 'r', 'k', '\n', '\0', ...};
您需要删除多余的换行符。
关于c - strstr() 不适用于 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26287060/
我是一名优秀的程序员,十分优秀!