Invalid input value while using char and scanf “%h

2019-08-01 00:26发布

问题:

So this is the code

void main()
{
  unsigned char n,t;
  scanf("%hhu %hhu",&n,&t);
  printf("%hhu %hhu",n,t);
}

The problem is when I input 5 and 1 respectively, the output is 0 and 1. 0 for n and 1 for t. However, when I changed the type from char to int/unsigned, the output is right as expected: 5 and 1.

The question is why asking for (number) input with char gives invalid value?

回答1:

int main(void) please

scanf("%hhu %hhu",&n,&t);

here ---------- ^ ------^ unsigned char * is expected

same for printf("%hhu %hhu",n,t);

so change

char n,t;

to

unsigned char n,t;



回答2:

Besides that it is

int main(void) 

at least, you also might like to also add the necessary prototypes by including the appropriate header:

#include <stdio.h>


标签: c input char scanf