Reputation: 1
I wanted to make a little experiment with scanf(). I wanted to read a small (<=255) integer from the user and store it in a char type.
I did:
char ch;
scanf("%d",&ch);
It works, but I want to satisfy the compiler and not to get this warning:
warning: format specifies type 'int *'
but the argument has type 'char *' [-Wformat]
scanf("%d",&ch);
Any idea?
Upvotes: 0
Views: 75
Reputation: 213960
First of all, to store a value 0 - 255, you should never use char
. In fact you should never use char
for the intention of storing anything but characters and strings. This is because that type has implementation-defined signedness: Is char signed or unsigned by default?
You could do:
unsigned char val;
scanf("%hhu", &val);
Although it is often best practice to use the portable types from stdint.h
:
#include <stdint.h>
#include <inttypes.h> // (actually includes stdint.h internally)
uint8_t val;
scanf("%"SCNu8, &val);
Upvotes: 3