我仍然不明白 scanf
如何返回 EOF
值。程序在窗口中运行。
来自 scanf
描述:
"The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure."
代码是
int main()
{
int status,a1,a2,b1;
char str1[100];
b1=EOF;
printf("b1=%d\n",b1);
printf("Enter input\n");
status=scanf("%d%d",&a1,&a2);
printf("status=%d",status);
return 0;
}
案例1 输入:
hello
输出
status=0
案例2 输入:
^z (press CTRL-Z)
输出
staus=-1
情况1是否是第一次转换前输入失败?如果是第一次转换前输入失败 为什么scanf返回0。
在情况 2 中,我按 CTRL-Z 第一次输入,scanf 返回 -1 所以 scanf 返回 EOF 的唯一方法是按 CTRL-Z?如果没有,请用示例代码解释一下
最佳答案
scanf
逻辑相当简单。它返回:
EOF
如果根本无法从流中读取单个字符。EOF
如果只有前导空白字符,直到出现错误或文件结尾才能读取转换除了%c
、%s
或扫描集(因为前导空格不是这些转换的一部分。0
如果读取的第一个字符与扫描集不匹配,或者空格后的第一个字符与标量转换的格式不匹配。- 否则它至少返回
1
。
关于c - 从 SCANF 返回 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58578912/