【发布时间】:2017-04-03 06:48:36
【问题描述】:
当尝试将“24”的八进制值读入无符号整数时,我得到 0。只需将十进制值作为 char 数组传入即可。
我需要一个 32 位无符号整数的最终值。初始值是从二进制文件中读入的。
MCVE
simple.cpp
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char count[4] = "\030\000\000"; // Just "24" works
__uint32_t value;
sscanf(count, "%x", &value);
fprintf(stderr, "%x", value);
return 0;
}
编译并使用
$ g++ simple.cpp -g
$ ./a.out
0
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
【问题讨论】:
-
你确实需要检查来自系统函数的返回值,比如
sscanf(),如果发布的代码已经检查了返回值,很明显对sscanf()的调用失败了。代码中的任何其他问题都是次要的