ungetc()
在某些角色上似乎失败了。下面是一个简单的测试程序:
#include <stdio.h>
int main(void) {
int c;
printf("Type a letter and the enter key: ");
#define TRACE(x) printf("%s -> %d\n", #x, x)
TRACE(c = getc(stdin));
TRACE(ungetc(c, stdin));
TRACE(getc(stdin));
TRACE(ungetc('\xFE', stdin));
TRACE(getc(stdin));
TRACE(ungetc('\xFF', stdin));
TRACE(getc(stdin));
return 0;
}
我在unix系统上运行它并键入a
按提示输入
输出如下:
Type a letter and the enter key: a
c = getc(stdin) -> 97
ungetc(c, stdin) -> 97
getc(stdin) -> 97
ungetc('\xFE', stdin) -> 254
getc(stdin) -> 254
ungetc('\xFF', stdin) -> -1
getc(stdin) -> 10
我预料到:
Type a letter and the enter key: a
c = getc(stdin) -> 97
ungetc(c, stdin) -> 97
getc(stdin) -> 97
ungetc('\xFE', stdin) -> 254
getc(stdin) -> 254
ungetc('\xFF', stdin) -> 255
getc(stdin) -> 255
为什么ungetc()
失败?
发布于 2018-06-15 17:09:08
根据以下假设进行工作:
'\xFF'
是-1
您的系统上(超出范围的字符常量的值是实现定义见下文)。EOF
是-1
您的系统上。该调用ungetc('\xFF', stdin);
与ungetc(EOF, stdin);
C11 7.21.7.10/4涵盖的行为相同:
如果该值
c
等于宏的值EOF
,则操作失败并且输入流不变。
输入范围ungetc
与输出范围(getchar
即EOF
负值)相同,或者表示字符的非负值(负值字符表示为转换为unsigned char
)。我认为你是为了ungetc(255, stdin);
。
关于值'\xFF'
,请参阅C11 6.4.4.4/10:
包含不映射到单字节执行字符的字符或转义序列的整数字符常量的值是实现定义的。
此外,执行字符集的值是实现定义的(C11 5.2.1 / 1)。你可以检查编译器文档以确定,但编译器行为表明它255
不在执行字符集中; 事实上,我测试过的gcc版本的行为表明它将范围char
作为执行字符集(而不是范围unsigned char
)。
https://stackoverflow.com/questions/-100008683
复制相似问题