How to write two unsigned char variables in c

Asked

Viewed 46 times

0

I’m having trouble writing two variables of type unsigned char using scanf, only the second value is saved in variable, I imagine it is buffer with garbage tried to treat and even so did not succeed, follow my attempt someone can help would be nice

    unsigned char dividendo = 0;
    unsigned char divisor = 0;  
    unsigned char c = 0;

    // entradas do usuario 
    printf ("\nDenominador:\n>> ");
    scanf ("%d", &dividendo);
    printf ("\nDivisor:\n>> ");
    while((c = getchar()) != '\n' && c != EOF);
    scanf ("%d", &divisor);

1 answer

4


You want to read variables of unsigned char type with scanf(), because then use %c format specifier, not %d.

I imagine it is buffer with garbage I tried to treat and still not succeeded

It is not "garbage in the buffer", because nothing that remains of a reading is garbage. scanf() is not meant to read data entered via keyboard, the user has at least 105 freedom keys, and keyboard input is not formatted at all. If you want to consume all the entered data, what you can do is read and ignore the typed ' n' by typing Enter at the end of the reading with the %*c specifier, see:

#include <stdio.h>

int main()
{
    int a;
    char b;

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

    printf("Letra: ");
    scanf("%c%*c", &b);

    printf("%d\n%c\n", a, b);

    return 0;
}

Experiment without %*c and see the ' n' read on the second scanf() call, preventing the user from typing the intended.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.