sscanf 对于带前导零的八位和九位不能正常工作

stu*_*lli 1 c integer constants scanf conversion-specifier

sscanf()我一直在尝试使用带有前导零的字符串(例如“03”)扫描整数。

然而,它工作正常,但只能到“07”。从“08”开始,字符串将被读取为 0。

您将在下面找到我的代码和输出。感谢您的帮助!

#include <stdio.h>
#include <stdlib.h>

int main() {

    char string_six[3] = "06";
    char string_seven[3] = "07";
    char string_eight[3] = "08";
    char string_nine[3] = "09";

    int six = -1;
    int seven = -1;
    int eight = -1;
    int nine = -1;

    sscanf(string_six, "%i", &six);
    sscanf(string_seven, "%i", &seven);
    sscanf(string_eight, "%i", &eight);
    sscanf(string_nine, "%i", &nine);

    printf("Six: %i\n",six);
    printf("Seven: %i\n",seven);
    printf("Eight: %i\n",eight);
    printf("Nine: %i\n",nine);

    return 0;    
}
Run Code Online (Sandbox Code Playgroud)

输出:

Six: 6
Seven: 7
Eight: 0
Nine: 0
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 6

您需要使用转换说明符%d而不是%i.

来自 C 标准(7.21.6.2 fscanf 函数)

d匹配一个可选的有符号十进制整数,其格式与 strtol 函数的主题序列的预期格式相同,基参数值为 10。相应的参数应是指向有符号整数的指针。

i匹配一个可选的有符号整数,其格式与 strtol 函数的主题序列的预期格式相同,基参数值为 0。相应的参数应是指向有符号整数的指针。

以及(7.22.1.4 strtol、strtoll、strtoul 和 strtoull 函数)

3 如果 base 的值为零,则主题序列的预期形式是整数常量的形式,如 6.4.4.1 中所述,前面可以选择加号或减号,但不包括整数后缀。

最后(6.4.4.1 整数常量)

integer-constant:
    decimal-constant integer-suffixopt
    octal-constant integer-suffixopt
    hexadecimal-constant integer-suffixopt
Run Code Online (Sandbox Code Playgroud)