Pukka
Pukka

Reputation: 31

Using user input value of unsigned char instead of the generated value behind the unsigned char

I have an algorithm which works perfectly with int but my input needs to be an unsigned char:

unsigned char a;

printf("a:");
scanf("%c",&a);

and because of this the algorithm doesn't take the Input 4 as 4 but instead 52 (ASCII). So my question: is there a way I can use the input 4 as a 4 in my calculations without changing the %c in the input code?

Upvotes: 0

Views: 97

Answers (3)

0___________
0___________

Reputation: 67476

Or if you insist to use %c

    unsigned char x,y;
    const char digits[] = "0123456789";

    x = scanf("%c", &x) == 1 ? x - '0' : -1;  //<-- less portable and no check 
 
    y = scanf("%c", &y) == 1 ? (isdigit(y) ? (strchr(digits, y) - digits) : -1 ): -1;
    //^^^^ a bit more portable and more checks

Upvotes: 1

chux
chux

Reputation: 153447

Since C99, use — length modifier "hh".

scanf("%hhu",&a);

Pre C-99, read via an unsigned

unsigned u;
scanf("%u",&u);
a = u;

Upvotes: 3

Eric Postpischil
Eric Postpischil

Reputation: 222536

Change scanf("%c",&a); to scanf("%hhu",&a);.

Upvotes: 2

Related Questions