首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么ungetc在某些字符上失败?

为什么ungetc在某些字符上失败?
EN

Stack Overflow用户
提问于 2018-06-15 07:43:23
回答 1查看 0关注 0票数 0

ungetc()在某些角色上似乎失败了。下面是一个简单的测试程序:

代码语言:txt
复制
#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按提示输入

输出如下:

代码语言:txt
复制
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

我预料到:

代码语言:txt
复制
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()失败?

EN

回答 1

Stack Overflow用户

发布于 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与输出范围(getcharEOF负值)相同,或者表示字符的非负值(负值字符表示为转换为unsigned char)。我认为你是为了ungetc(255, stdin);

关于值'\xFF',请参阅C11 6.4.4.4/10:

包含不映射到单字节执行字符的字符或转义序列的整数字符常量的值是实现定义的。

此外,执行字符集的值是实现定义的(C11 5.2.1 / 1)。你可以检查编译器文档以确定,但编译器行为表明它255不在执行字符集中; 事实上,我测试过的gcc版本的行为表明它将范围char作为执行字符集(而不是范围unsigned char)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100008683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档