sscanf()的行为不一致

时间:2017-01-27 07:55:46

标签: c scanf

所以我发现了一个非常奇怪的sscanf()函数行为。 我有以下代码解析给定的Date字符串:

ViewCompat.setTranslationX(indicatorView, seekBarProgress)

输出如下:

#include <stdio.h>

int main()
{
    int year, month, day;

    sscanf("20151106","%4i%2i%2i",&year,&month,&day);
    printf("Year: %04i\tMonth: %02i\tDay: %02i\n",year,month,day);

    sscanf("20151107","%4i%2i%2i",&year,&month,&day);
    printf("Year: %04i\tMonth: %02i\tDay: %02i\n",year,month,day);

    sscanf("20151108","%4i%2i%2i",&year,&month,&day);
    printf("Year: %04i\tMonth: %02i\tDay: %02i\n",year,month,day);

    sscanf("20151109","%4i%2i%2i",&year,&month,&day);
    printf("Year: %04i\tMonth: %02i\tDay: %02i\n",year,month,day);

    sscanf("20151110","%4i%2i%2i",&year,&month,&day);
    printf("Year: %04i\tMonth: %02i\tDay: %02i\n",year,month,day);

    sscanf("20151111","%4i%2i%2i",&year,&month,&day);
    printf("Year: %04i\tMonth: %02i\tDay: %02i\n",year,month,day);


    return 0;
}

为什么sscanf()错误地解析08.和09.日?

提前致谢!

了Jorg

1 个答案:

答案 0 :(得分:4)

那是因为你正在使用&#34;我&#34;而不是&#34; d&#34;。当使用&#34; i&#34; format,以0x开头的数字作为基数16读取,以0开头的数字作为基数8。

因此,01到07在基数8和10中是相同的,所以你得到正确的值,但08是零而09是无效的。

更改您的代码以使用&#34; d&#34;说明符,例如:

#include <stdio.h>

int main()
{
    int year, month, day;

    sscanf("20151108","%4d%2d%2d",&year,&month,&day);
    printf("Year: %04d\tMonth: %02d\tDay: %02d\n",year,month,day);

    return 0;
}

输出:

Year: 2015  Month: 11   Day: 08