gpt4 book ai didi

c++ - sscanf 中 uint16_t 的正确且可移植的 (Clang/GCC) 修饰符是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:27:49 27 4
gpt4 key购买 nike

当我尝试编译这段代码时收到一条警告消息sscanf(value, "%h"PRIu16 "B", &packet_size) 使用 Clang 600.0.57 (OS X)。

warning: format specifies type 'unsigned char *' but the argument has type 'uint16_t *'
(aka 'unsigned short *') [-Wformat]
if (sscanf(value, "%h" PRIu16 "B", &packet_size) == 1) {
~~~~ ^~~~~~~~~~~~

但是如果我删除修饰符“h”,那么我会在 GCC 4.8.3 (Scientific Linux 7) 中收到以下错误。

warning: format ‘%u’ expects argument of type ‘unsigned int*’, but argument 3 has type ‘uint16_t* {aka short unsigned int*}’ [-Wformat=]
if (sscanf(value, "%" PRIu16 "B", &packet_size) == 1) {

^

sscanf 中 uint16_t* 的正确且可移植的修饰符是什么?

=== 在下面添加了更多不言自明的示例 ===

测试.c

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS 1
#endif
#include <inttypes.h>
#include <stdio.h>

int main() {
char* str = "16 bits";
uint16_t u16;
sscanf(str, "%h" PRIu16 " bits", &u16); // Clang warning
sscanf(str, "%" PRIu16 " bits", &u16); // GCC warning
sscanf(str, "%" SCNu16 " bits", &u16); // OK for both compilers

printf("%" PRIu16 " bits\n", u16);

return 0;
}

Clang 警告

$ clang test.c -Wall -Wextra
test.c:10:36: warning: format specifies type 'unsigned char *' but the argument
has type 'uint16_t *' (aka 'unsigned short *') [-Wformat]
sscanf(str, "%h" PRIu16 " bits", &u16); // Clang warning
~~~~ ^~~~
1 warning generated.

海湾合作委员会警告

$ gcc -Wall -Wextra test.c
test.c: In function ‘main’:
test.c:11:3: warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 3 has type ‘uint16_t *’ [-Wformat=]
sscanf(str, "%" PRIu16 " bits", &u16); // GCC warning
^

最佳答案

正如@EOF 在他们的评论中所说,fscanffprintf每个都有自己的宏。

final C99 draft , §7.8.1 第 4 条和第 5 条(第 199 页)说 <inttypes.h>应定义以下宏:

  1. The fscanf macros for signed integers are:

    SCNdN SCNdLEASTN SCNdFASTN SCNdMAX SCNdPTR
    SCNiN SCNiLEASTN SCNiFASTN SCNiMAX SCNiPTR

  2. The fscanf macros for unsigned integers are:

    SCNoN SCNoLEASTN SCNoFASTN SCNoMAX SCNoPTR
    SCNuN SCNuLEASTN SCNuFASTN SCNuMAX SCNuPTR
    SCNxN SCNxLEASTN SCNxFASTN SCNxMAX SCNxPTR

如果你想阅读uint16_t作为十进制数 fscanf , 你必须使用 SCNu16 .

例子:

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

int main(void) {
uint16_t input;

int items = scanf("fetch %" SCNu16 " bits", &input);

if (items == 1) {
printf("I'm busy, go fetch those %" PRIu16 " bits yourself.\n", input);
} else {
printf("I don't understand what you're saying.\n")
}

return 0;
}

关于c++ - sscanf 中 uint16_t 的正确且可移植的 (Clang/GCC) 修饰符是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33675163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com