c - C 程序中的文件结尾 (EOF)

标签 c eof getchar

我制作了一个简单的 C 程序,需要在输入 EOF 字符(Windows 为 Ctrl-Z)时完成并打印:

  • 如果成绩高于或等于 5,则通过。
  • 如果等级高于或等于 8,则通过 High Pass。
  • 任何其他情况均未通过。

我使用 getchar() 进行用户输入(在本例中为成绩)。

#include <stdio.h>

int main() {
    int grade;
    puts("Enter a grade\n");
    puts("Enter the EOF character to end input\n");

    while ((grade = getchar()) != EOF) {
        if (grade >= 5) {
            puts("Passed");
            if (grade >= 8) {
                puts("with High Pass\n");
            }
        } else {
            puts("Failed\n");
        }
    }
    return 0;
}

问题是程序没有做应该做的事情,如果你能帮我找到解决方案,我将不胜感激。

最佳答案

程序没有按预期运行有两个原因:

  • stdin 读取的字节不是数值:如果用户输入 1,程序接收到的是 '1'字符值,而不是数值。您可以通过减去 '0' 的字符值来计算数字字符的数值:

    int c = getchar();
    if (c >= '0' && c <= '9') {
        int grade = c - '0';
        /* you can now test the grade */
    
  • 您一次读取一个字节的标准输入:它不允许超过 9 的成绩。如果用户键入 10,您将测试 2 个等级并输出 Failed! 两次。

这是使用 scanf() 的替代版本:

#include <stdio.h>

int main(void) {
    int grade;
    puts("Enter the grades\n");
    puts("Enter the EOF character to end input\n");

    while (scanf("%d", &grade) == 1) {
        if (grade >= 8) {
            puts("Passed with High Pass");
        } else
        if (grade >= 5) {
            puts("Passed");
        } else {
            puts("Failed\n");
        }
    }
    return 0;
}

关于c - C 程序中的文件结尾 (EOF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45649324/

相关文章:

c++ - C++/VIM 与其他 IDE 相比奇怪的 EOF 行为

C++从文件函数读取无法在循环时退出

c - 我的代码在 C 中看不到 while 循环(使用 getchar 函数)

c - 如何避免使用 getchar() 按下 Enter 来仅读取单个字符?

c - 删除 Kernighan 和 Ritchie 的评论程序

C编程: Write a program that reads three integers from keyboard and outputs their sum

c - 链接需要链接两个相互依赖的静态库 : undefined reference

python - 如何找出文件是否位于 `eof` ?

c - getchar() 和缓冲区顺序

c - 无法使用最新的 ffmpeg 库解码 mp4 文件 : av_decode_video2