[英]Can this code work with fgets?
以下代码可与scanf
,但我不知道如何使其与fgets
(搜索始终会失败),请您帮我一下(我是C语言的初学者)?
如果可能的话,您能告诉我为什么它似乎不适用于fgets
吗?
#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",
};
int main(){
char word[80];
puts("Hello, type a word: ");
fgets(word, 80, stdin);
// scanf("%79s", word);
for( int i= 0; i < 5; i++){
if( strstr(tracks[i], word) ){
printf("Found the track: %s\n", tracks[i]);
break;
}
}
return 0;
}
fgets(word, 80, stdin)
和scanf("%79s", word)
之间的区别在于, fgets
在空终止符之前将包含'\\n'
,而scanf
不会。 这就是为什么strstr
使用fgets
返回NULL
原因:结尾处没有匹配的'\\n'
。
有两种使字符串再次相等的通用方法-您可以从word
的末尾删除'\\n'
(首选),也可以在搜索到的单词的末尾添加'\\n'
(不建议) 。
int len = strlen(word);
if (len != 0 && word[len-1] == '\n') {
word[len-1] = '\0';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.