9 || num<" /> 9 || num<" /> 9 || num<"/>

scanning an integer ONLY into an array

233 views Asked by At

As a part of an assignment I've got, I need to get from a user a digit only using the <stdio.h> library.

do {
  scanf("%d",&num);
} while (num>9 || num<0);

But the program will get from the user also chars and other things.

Any advice?

2

There are 2 answers

0
Pranav Totla On BEST ANSWER

One way of solving this is getting the ASCII value of the scanned "digit" and making sure it lies between ASCII values 0X30 and 0X39 (or 48 and 57).

Seeing your logic, you seem to be interested in numbers greater than 9 (multiple digit numbers) and numbers less than 0 (signed numbers/integers).

I suggest instead of using scanf better use something like getchar which will return one character at a time.

A simple way to scan multiple digit numbers using getchar can be:

int getNumber()
{
    int sign = 1;
    int i = 0;
    int ch;
    ch = getchar();
    if((ch == '-') || (ch == '+')) //check sign
    {
        if(ch == '-') sign = -1;
    }
    else  
    {
        if (ch > '9' || ch < '0')
            return NULL; // Your requirement - it's a non number
        i *= 10;
        i += ch - '0';
    }
    while ((ch = getchar()) != '\n') //get remaining chars
    {
        if (ch > '9' || ch < '0')
            return NULL; // Your requirement - it's a non number
        i *= 10;
        i += ch - '0';
    }
    i *= sign; //change sign
    return i;
}

You can call this function in place of scanf.

7
yoker On

You can use getchar() to read a single character from stdin and then compare it to the ASCII values for 0 and 9 (your upper and lower bounds for a single character). The digit as an integer is equal to the character code minus the character code for 0.

#include <stdio.h>

int main(void) {
    char c;

    while((c = getchar()) >= '0' && c <= '9')
        printf("Digit is: %d\n", c - '0');
    return 0;
}