Scanf () discards the first result depending on the order of the variable declaration

Why is this not working properly?

int main()
{
    unsigned char louise, peter;

    printf("Age of Louise: ");
    scanf("%u", &louise);

    printf("Age of Peter: ");
    scanf("%u", &peter);

    printf("Louise: %u\n", louise);
    printf("Peter: %u\n", peter);

    return 0;
}

Outputs:

Age of Louise: 12
Age of Peter: 13
Louise: 0
Peter: 13

But if I change variable declarations, it works:

unsigned char peter, louise;

Outputs:

Age of Louise: 12
Age of Peter: 13
Louise: 12
Peter: 13

I also noticed that using intor unsigned intworks without having to replace variables, but chardoes not work.

I tried to deliver printf("%u", louise);immediately after scanf()for louise, and the value will be saved correctly. And if I comment on the second scanf(), it also works great ...

"Problem" is displayed on Windows (DevCpp) and Linux (kwrite + make). Is this a compiler or mine error?

+3
source share
2 answers

, unsigned char, 1 , 12, 4 ( int), ( / ) , . %u printf, unsigned int, unsigned char, . , , unsigned int int, .

, , , .

+1

%u unsigned int, , , , unsigned char, . .

(, "42" ) char. int. :

int tmp;
char my_char;

if(scanf("Enter a number: %d", &tmp) == 1)
{
  my_char = (unsigned char) tmp;
}
+4

Source: https://habr.com/ru/post/1731212/


All Articles