为什么ungetc在某些角色上失败?

chq*_*lie 6 c language-lawyer ungetc

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;
}
Run Code Online (Sandbox Code Playgroud)

我在unix系统上运行它并a Enter在提示符下输入

输出是:

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
Run Code Online (Sandbox Code Playgroud)

我期待这个:

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
Run Code Online (Sandbox Code Playgroud)

为什么导致ungetc()失败?

编辑:更糟糕的是,我在不同的unix系统上测试了相同的代码,并且它在那里表现得如预期的那样.有某种未定义的行为吗?

M.M*_*M.M 4

根据以下假设开展工作:

  • 您所在的系统对普通字符进行了签名。
  • '\xFF'位于-1您的系统上(超出范围的字符常量的值是实现定义的,请参见下文)。
  • EOF-1您的系统上。

该调用与 C11 7.21.7.10/4 所涵盖的行为ungetc('\xFF', stdin);相同:ungetc(EOF, stdin);

如果 的值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)。