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/34816138/

相关文章:

c - 如何在 Mac 操作系统上等待用户的操作?

C 输入 - getchar()

c - 在 C 中返回二维数组的数组

c - 对 2D 数组使用 malloc 时出现段错误

c - 尝试打印出所有输入字符的 getchar() != EOF 的返回值

windows - 重置非空文件后,Freepascal 发现 eof

c - 为什么 printf ("%d", getchar()) 打印额外的 10

c - gdb中如何处理单行换行成多行?

c - C if 语句条件中 & 符号的使用

c++ - 读取和打印文件中的值