Windows 系统上的getchar() 和scanf() 中的EOF 是如何作用的?
How does EOF act in getchar() and scanf() on Windows system?
我有两段代码来测试两个控制台 I/O 函数 getchar() 和 scanf() 如何处理 EOF。但是我仍然对输出及其行为背后的实际操作没有清晰的理解。有人可以为我解释一下吗?非常感谢! (我正在使用 Windows OS)
// 1st piece of Code
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
while ((ch=getchar()) != EOF)
{
putchar(toupper(ch));
}
return 0;
}
如果我输入
abc
或
abc(ctrl+z)
The program will have the same outputs:
ABC
// 2nd piece of Code
#include<stdio.h>
int main(void)
{
int x;
while(scanf("%d",&x) != EOF)
{
/*Ctrl + z + Enter*/
printf("x=%d\n",x);
}
return 0;
}
如果我输入
123
The program will output:
x=123
否则,如果我输入
123(ctrl+z)
The program will have an infinite output:
x=123
x=123
x=123
x=123
...
问题是在 Windows 上 EOF
像普通字符一样被放入输入缓冲区(具有编码值 26
)。
当逐个字符读取时(例如 getchar
),这是由 Windows 运行-time 库处理的。但它不像 scanf
那样工作,因为当 scanf
解析输入时,它就像另一个字符。作为非数字,它是 te "%d"
格式的无效字符,导致您 scanf
调用 return 0
而不是 EOF
(因为它不是按格式解析)。
解决它的一种方法是在其自己的新行上按 Ctrl-Z 序列。
另一种(也是更可靠的)解决方法是检查 scanf
return 字符串中的格式数。在您的情况下,您应该与 1
进行比较(因为您有一个格式说明符)。
getchar()
returns字符的值转换为unsigned char
或EOF
以防出错。
错误可能是"end of file"或其他;通常(对于 getchar()
)程序员不关心错误,只关心发生错误。
scanf()
returns 匹配和分配的值的数量(基本上是格式字符串中 %
的数量)或 EOF
错误的情况。 请注意,该数字可以小于 %
的数字,例如,输入格式错误
就像 getchar()
一样,错误可能是 "end of file" 或其他。特别是,读取数量少于%
不是错误。
所以您可能更愿意测试正确的作业数量,而不是测试 scanf()
中的错误
#include <stdio.h>
int main(void) {
int x;
while (scanf("%d", &x) != 1) {
/*Ctrl + z + Enter*/
printf("x=%d\n", x);
}
return 0;
}
我有两段代码来测试两个控制台 I/O 函数 getchar() 和 scanf() 如何处理 EOF。但是我仍然对输出及其行为背后的实际操作没有清晰的理解。有人可以为我解释一下吗?非常感谢! (我正在使用 Windows OS)
// 1st piece of Code
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
while ((ch=getchar()) != EOF)
{
putchar(toupper(ch));
}
return 0;
}
如果我输入
abc
或
abc(ctrl+z)
The program will have the same outputs:
ABC
// 2nd piece of Code
#include<stdio.h>
int main(void)
{
int x;
while(scanf("%d",&x) != EOF)
{
/*Ctrl + z + Enter*/
printf("x=%d\n",x);
}
return 0;
}
如果我输入
123
The program will output:
x=123
否则,如果我输入
123(ctrl+z)
The program will have an infinite output:
x=123
x=123
x=123
x=123
...
问题是在 Windows 上 EOF
像普通字符一样被放入输入缓冲区(具有编码值 26
)。
当逐个字符读取时(例如 getchar
),这是由 Windows 运行-time 库处理的。但它不像 scanf
那样工作,因为当 scanf
解析输入时,它就像另一个字符。作为非数字,它是 te "%d"
格式的无效字符,导致您 scanf
调用 return 0
而不是 EOF
(因为它不是按格式解析)。
解决它的一种方法是在其自己的新行上按 Ctrl-Z 序列。
另一种(也是更可靠的)解决方法是检查 scanf
return 字符串中的格式数。在您的情况下,您应该与 1
进行比较(因为您有一个格式说明符)。
getchar()
returns字符的值转换为unsigned char
或EOF
以防出错。
错误可能是"end of file"或其他;通常(对于 getchar()
)程序员不关心错误,只关心发生错误。
scanf()
returns 匹配和分配的值的数量(基本上是格式字符串中 %
的数量)或 EOF
错误的情况。 请注意,该数字可以小于 %
的数字,例如,输入格式错误
就像 getchar()
一样,错误可能是 "end of file" 或其他。特别是,读取数量少于%
不是错误。
所以您可能更愿意测试正确的作业数量,而不是测试 scanf()
#include <stdio.h>
int main(void) {
int x;
while (scanf("%d", &x) != 1) {
/*Ctrl + z + Enter*/
printf("x=%d\n", x);
}
return 0;
}