Reading a positive number in C

I am trying to find the most efficient way to read in a positive number in C. I cannot only use scanf ("% u", & var) because scanf accepts two complements of negative numbers, thereby screwing up the number. I also do not want to read characters manually into the buffer, because it requires me to know the maximum number of digits, which in fact I want to limit only to UINT_MAX.

Any ideas, things that I most likely did not notice?

+5
source share
2 answers

Maybe something like:

char sign = getchar();
if ('-' == sign) {
    //error
} else {
    ungetchar(sign);
    scanf("%u", &var) 
}
+5
source

signed int , , :

int var;
scanf("%d", &var);

if (var < 0) {
    printf("Error: %d is negative", var);
}
else {
    /* use the positive number */
    unsigned int positive = var;
    /* ... */
}
0

All Articles