c - EOF 宏如何与 getchar 一起使用?

标签 c eof getchar

#include<stdio.h>

int main(void) {
    FILE *fp;
    int ch;
    fp = fopen("input.txt", "w");
    printf("Enter data");
    while ((ch = getchar()) != EOF) {
        putc(ch, fp);
    }
    fclose(fp);
    fp = fopen("input.txt", "w");
    while ((ch = getc(fp)) != EOF) {
        printf("%c", ch);
    }
    fclose(fp);
}

第一个 while 循环如何停止用户输入? 由于存在 EOF 作为条件。

否则我需要使用 for 循环吗?

最佳答案

EOF是一个值,而不是一个函数。它本质上被定义为一个宏。

供引用,来自C11 ,第 §7.21.1 章,<stdio.h>

EOF
which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;[...]

以防万一, getchar() 失败,它将返回一个定义为 EOF 的值.

引用手册页(强调我的)

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

EOF表示可能不适合 char 的值类型。您必须使用int输入 ch变量。

How does the first while loop stop inputting from user?

在 Linux 上使用 CTRL+D,在 Windows 上使用 CTRL+Z

关于c - EOF 宏如何与 getchar 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55276000/

相关文章:

c - 如何在 Windows WDM 驱动程序中设置系统时间?

c - Rcpp 中单个 "for"循环的意外性能

c - 使用 SSE 实现高斯消元

c - 字数统计程序 - stdin

c - 在 C 中处理输入

c++ - 使用 getchar() 和 -O3 的奇怪行为

C - 使用指针和函数的 for 循环出现段错误

c - 使用 fgets 达到 EOF

c - EOF和普通整数有什么区别?

c - 将文本中的空格限制为只有一个 - c