gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:07 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com