我写了一个简短的程序来测试从以下位置读取文本文件stdin
:
int main(){
char c;
while(!feof(stdin)){
c = getchar(); //on last iteration, this returns '\n'
if(!isspace(c)) //so this is false
putchar(c);
//remove spaces
while (!feof(stdin) && isspace(c)){ //and this is true
c = getchar(); // <-- stops here after last \n
if(!isspace(c)){
ungetc(c, stdin);
putchar('\n');
}
}
}
return 0;
}
然后我将它传递给一个小文本文件:
jimmy 8
phil 6
joey 7
最后一行 ( joey 7
) 以字符结尾\n
。
我的问题是,在它读取并打印最后一行之后,然后循环返回以检查更多输入,没有更多字符要读取,它只是停在代码块中注明的行。
feof()
问题:返回 true的唯一方法是在读取失败后,如下所述: Detecting EOF in C。为什么不是getchar
触发 EOF 的最终调用以及如何更好地处理此事件?