#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 typeint
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()
andgetchar()
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/