Jorg Angelov
Jorg Angelov

Reputation: 21

Inconsistent Behavior of sscanf()

So I discovered a really weird behaviour of the sscanf() function. I have the following Code that parses given strings of Date:

#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;
}

And the Output is the following:

Year: 2015      Month: 11       Day: 06
Year: 2015      Month: 11       Day: 07
Year: 2015      Month: 11       Day: 00
Year: 2015      Month: 11       Day: 00
Year: 2015      Month: 11       Day: 10
Year: 2015      Month: 11       Day: 11

Why does sscanf() parse the 08. and 09. day incorrectly?

Thanks in advance!

Jorg

Upvotes: 1

Views: 118

Answers (1)

Guillaume
Guillaume

Reputation: 10961

That's because you're using "i" and not "d". When using the "i" format, Number starting with 0x are read as base 16 and numbers starting with 0 as base 8.

So, 01 to 07 are the same in base 8 and 10, so you're getting the correct values, but 08 is zero and 09 is invalid.

Change your code to use the "d" specifier, for example :

#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;
}

outputs:

Year: 2015  Month: 11   Day: 08

Upvotes: 4

Related Questions