[英]function doesn't detect EOF
Function get_word is supposed to read word from stdin and save it.函数 get_word 应该从 stdin 读取单词并保存它。 Saving next word after white char and return EOF on EOF but I am still getting in infinite loop.在白色字符之后保存下一个单词并在 EOF 上返回 EOF 但我仍然陷入无限循环。 htab_lookup_add is some function to save word into table. htab_lookup_add 是一些将单词保存到表中的函数。 There also seems to be a problem "Too long message" never prints but that's not the problem I am trying to solve now.似乎还有一个问题“消息太长”永远不会打印,但这不是我现在想要解决的问题。
int get_word(char *s, int max, FILE *f){
s = malloc(sizeof(char) * max);
int c;
int i = 0;
while((c = getc(f))){
if(i > max || isspace(c)){
break;
}
s[i++] = c;
}
s[i] = '\0';
if(c == EOF){
return EOF;
}
return i;
}
while(get_word(word, (maxchar + 1), stdin) != EOF){
if(strlen(word) > maxchar){
printf("Too long!\n");
}
htab_lookup_add(table, word);
}
This loop:这个循环:
while((c = getc(f))){
...
}
will terminate only when getc()
returns zero, ie, when it reads a null character '\\0'
.仅当getc()
返回零时才会终止,即当它读取空字符'\\0'
。 And when it returns EOF
you'll store that value (converted to char
) in s[i]
and continue looping.当它返回EOF
时,您将将该值(转换为char
)存储在s[i]
并继续循环。
The test for EOF
after the loop will never match.循环后的EOF
测试永远不会匹配。
You need to end the loop when it returns EOF
.当它返回EOF
时,您需要结束循环。 The usual idiom is:通常的成语是:
while ((c = getc(f)) != EOF) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.