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

End of File (EOF) in C program

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

我使用 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;
}

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

您得到的是输入数字的 ascii 码,而不是它的值。转换为比较前的数字。

while ((grade = getchar()) != EOF) {
    getchar();  // flush the \n
    if (isdigit(grade))
    {
        int intgrade = grade - '0';

        if (intgrade >= 5) {
            puts("Passed");
            if (intgrade >= 8) {
                puts("with High Pass\n");
            }
        }
        else {
            puts("Failed\n");
        }
    }
    else printf("Wrong entry\n");
}

return 0;

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

  • 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;
}