c++ - sscanf 从八进制转换:它怎么知道?
问题描述
我有这个将字符串转换为 int 的代码
unsigned int formatInt(char *ptr) {
int res;
if (sscanf(ptr, "%i", &res) == -1) exit(-1);
return res;
}
我喂它char *
指向“00000000041”的第一个字符。
转换为int
返回我 33(隐式八进制到十进制转换)
"00000000041" 实际上是一个字符串 ( char[12]
),但它是八进制文件的大小。
编译器怎么知道它是八进制的?00000000041 完全可以是小数 (41)
解决方案
将字符串识别为八进制是%i
格式说明符 to的函数scanf
。从手册页:
i Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.
因此,因为字符串以 0 开头%i
并被使用,所以它被解释为八进制字符串。
推荐阅读
- python-3.x - 如何合并这个字典列表?
- python - 查询从 numpy 数组中取值
- html - Edge 中带有不必要的垂直滚动条的页面
- java - swt 菜单上单击隐藏显示复合
- azure-resource-manager - 429错误时如何在Azure帐户中增加读取次数请求限制
- sql - 在包含顶级 UNION INTERSECT 或 EXCEPT 运算符的语句中不允许变量赋值
- pandas-groupby - pandas groupby 提取前百分比 n 数据(降序)
- android - 在颤振应用程序中获得互联网许可
- tcp - 尝试通过 AT 命令连接到 4G GSM 模块时 TCP/IP 连接被拒绝
- c# - 如何在 C# 中反序列化这个 xml 数据?