0

我写了一个简短的程序来测试从以下位置读取文本文件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 的最终调用以及如何更好地处理此事件?

4

1 回答 1

2

您的代码中有多个问题:

  • 您不包括<stdio.h>, 也不<ctype.h>,或者至少您没有发布整个源代码。
  • feof()用来检查文件的结尾。这几乎从来都不是正确的方法,正如为什么“while (!feof (file))”总是错误的?
  • 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;
}

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

#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;
}
于 2016-09-04T18:48:53.300 回答