[英]Can this code work with fgets?
The following code works with scanf
, but I don't know how to make it work with fgets
(the search always fails), could you help me please (I'm a beginner in C) ? 以下代码可与
scanf
,但我不知道如何使其与fgets
(搜索始终会失败),请您帮我一下(我是C语言的初学者)?
And if possible, could you tell me why it doesn't seem to work with fgets
? 如果可能的话,您能告诉我为什么它似乎不适用于
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;
}
The difference between fgets(word, 80, stdin)
and scanf("%79s", word)
is that fgets
one will include '\\n'
before null terminator, while scanf
would not. fgets(word, 80, stdin)
和scanf("%79s", word)
之间的区别在于, fgets
在空终止符之前将包含'\\n'
,而scanf
不会。 That is why strstr
returns NULL
with fgets
: there is an unmatched '\\n'
at the end. 这就是为什么
strstr
使用fgets
返回NULL
原因:结尾处没有匹配的'\\n'
。
There are two general approaches to making the strings equal again - you could either remove the '\\n'
from the end of the word
(preferred), or add '\\n'
to the end of the words that you search (not recommended). 有两种使字符串再次相等的通用方法-您可以从
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.