从 stdin 读取文本文件在最后一行停止

Reading text file from stdin stops at last line

我写了一个小程序来测试从 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() 变为 return 的唯一方法是在读取失败后,如此处所述:Detecting EOF in C。为什么对 getchar 的最终调用没有触发 EOF,我怎样才能更好地处理这个事件?

您的代码中存在多个问题:

  • 您没有包含 <stdio.h>,也没有 <ctype.h>,或者至少您没有 post 整个源代码。
  • 您使用 feof() 检查文件结尾。正如 Why is “while ( !feof (file) )” always wrong?
  • 中强调的那样,这几乎从来都不是正确的方法
  • 您从 char 变量中的流中读取字节。这会阻止 EOF 的正确测试,还会导致 isspace(c) 出现未定义的行为。将类型更改为 int.

这是一个改进的版本:

#include <stdio.h>

int main(void) {
    int c;

    while ((c = getchar()) != EOF) {
        if (!isspace(c)) {
            putchar(c);
        } else {
            //remove spaces
            while ((c = getchar()) != EOF && isspace(c)) {
                continue;  // just ignore extra spaces
            }
            putchar('\n');
            if (c == EOF)
                break;
            ungetc(c, stdin);
        }
    }
    return 0;
}

虽然您使用 ungetc() 的方法在功能上是正确的,但最好以这种方式使用辅助变量:

#include <stdio.h>
#include <ctype.h>

int main(void) {
    int c, last;

    for (last = '\n'; ((c = getchar()) != EOF; last = c) {
        if (!isspace(c)) {
            putchar(c);
        } else
        if (!isspace(last))
            putchar('\n');
        }
    }
    return 0;
}