scanf无法扫描到uint8_t

Dil*_*ill 2 c

当我尝试使用scanfuint8_t,我会得到疯狂的结果.使用int,我得到预期的输出"08 - 15".使用uint8_t,我得到"00 - 15".

const char *foo = "0815";
uint8_t d1, d2; // output: 00 - 15 (!!!)
// int d1, d2;         // output: 08 - 15
sscanf(foo, "%2d %2d", &d1, &d2);
printf("%02d - %02d\n", d1, d2);
Run Code Online (Sandbox Code Playgroud)

我正在使用GCC.

Die*_*Epp 7

%d是错误的,因为这意味着你正在经过,int *但实际上你想要通过uint8_t *.您将需要使用适当的宏:

#include <inttypes.h>
...
sscanf(foo, "%2" SCNu8 " %2" SCNu8, &d1, &d2);
Run Code Online (Sandbox Code Playgroud)

大多数编译器应该给你关于你的代码版本的警告.这是Clang的输出:

test2.c:8:24: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
sscanf(foo, "%2d %2d", &d1, &d2);
             ~~~       ^~~
             %2s
test2.c:8:29: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
sscanf(foo, "%2d %2d", &d1, &d2);
                 ~~~        ^~~
                 %2s
2 warnings generated.

因为uint8_t,这不适用于printf(),因为在传递之前它将uint8_t始终被提升.intprintf()


Ker*_* SB 6

scanf 格式说明符%d表示“我保证给你一个int *”。如果您不提供int. 所有的赌注都落空了。(这是未定义的行为。)

道德:不要对编译器撒谎。