force scanf("") to only receive a number 0-7

I have a task to write a code that would receive a number from 0 to 7 (including edges) and convert it to 4bit binary code in two's complement.

everything is fine with my code. it works and calculation is fine. but I want to make things nicer by limiting the user from inputting a number that is not 0-7. right now users can put any number they want but it doesn't make sense in the conversion system...

how can I do that?

thanks...

1 answer

  • answered 2019-11-08 14:04 Vlad from Moscow

    You can do it something like that

    #include <stdio.h>
    
    int main(void) 
    {
        unsigned int digit;
    
        while ( scanf( "%u", &digit ) != 1 || 7 < digit )
        {
            scanf( "%*[^\n]" );
        }
    
        printf( "digit = %u\n", digit );
    
        return 0;
    }
    

    If the input is

    A
    8
    5
    

    then the output is

    digit = 5