简体   繁体   English

ANSI C(ISO C90):scanf可以读取/接受未签名的字符吗?

[英]ANSI C (ISO C90): Can scanf read/accept an unsigned char?

Simple question: Can scanf read/accept a "small integer" into an unsigned char in ANSI C? 一个简单的问题:scanf是否可以将ANSI C中的“小整数”读取/接受为无符号字符?

example code un_char.c: 示例代码un_char.c:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    unsigned char character;

    scanf("%hhu", &character);

    return EXIT_SUCCESS;
}

Compiled as: 编译为:

$ gcc -Wall -ansi -pedantic -o un_char un_char.c
un_char.c: In function ‘main’:
un_char.c:8: warning: ISO C90 does not support the ‘hh’ gnu_scanf length modifier

hh isn't supported by ISO C90. ISO C90不支持hh So what scanf conversion can be used in this situation? 那么在这种情况下可以使用什么scanf转换?

No: C89 (C90) does not support '%hhu' to read a string of digits into an unsigned char. 否:C89(C90)不支持'%hhu'将一串数字读入未签名的字符中。 That is a feature in C99. 这是C99的功能。

You would have to read into an unsigned integer ( '%u' ) or unsigned short ( '%hu' ) and then check that the result is with the range of an unsigned char. 您将必须读入无符号整数( '%u' )或无符号short( '%hu' ),然后检查结果是否在无符号char范围内。

将其读取为无符号的short / int,并在需要时进行一些范围检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM