C - 从最后一行的文件问题中读取

Lae*_*ica 0 c newline

我的程序对我的任务的预期输入是类似的 ./program "hello" < helloworld.txt.然而,问题在于我必须分析程序中的每一行,所以我使用了一个行的结尾作为:

while((c = getchar()) != EOF) {
    if (c == '\n') {
    /*stuff will be done*/
Run Code Online (Sandbox Code Playgroud)

但是,我的问题是如果helloworld.txt文件包含:

hello
world
Run Code Online (Sandbox Code Playgroud)

它只会读取第一行(如果有更多行,则直到第二行最后一行).

为了解决这个问题,我必须严格地制作一个新的行,helloworld.txt如下所示:

hello
world
//
Run Code Online (Sandbox Code Playgroud)

还有另一种方法吗?

Fer*_*ira 5

修复你的算法.代替:

while((c = getchar()) != EOF) {
    if (c == '\n') {
        /* stuff will be done */
    } else {
        /* buffer the c character */
    }
}
Run Code Online (Sandbox Code Playgroud)

做:

do {
    c = getchar();
    if (c == '\n' || c == EOF) {
        /* do stuff with the buffered line */
        /* clear the buffered line */
    } else {
        /* add the c character to the buffered line */
    }
} while (c != EOF);
Run Code Online (Sandbox Code Playgroud)

但请注意,如果是,则不应使用c变量的值EOF.