首页 > 解决方案 > 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)

标签: c++cscanf

解决方案


将字符串识别为八进制是%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并被使用,所以它被解释为八进制字符串。


推荐阅读