Search code examples
ciochartype-conversionmultiplication

C Programming: how to get normal value of int without using value - 48?


So i have this loop the check user input:

int ch, num;

while ((ch = getchar()) != '\n')
{
    if (isdigit(ch))
    {
        num = ch - 48;   
    }
}

So according this table:

Character   Decimal Value
0           48
1           49
2           50
3           51
4           52
5           53
6           54
7           55
8           56
9           57

I am using this way to get my number: num = ch - 48; And if for example i want to multiple my number by 10 ?


Solution

  • Here's the best way to read input from user till the new line. I'm posting one example you can go through it and implement your code as you need.

    This example will read for user input in integer untill newLine(\n). Make sure you are not giving space at last.

    Sample Code:

    #include <stdio.h>
    int main(void) {
        int i=0,size,arr[10000];
        char temp; 
        do{
            scanf("%d%c", &arr[i], &temp); 
            i++; 
            } while(temp!= '\n');
    
        size=i; 
    
        for(i=0;i<size;i++){ 
            printf("%d ",arr[i]); 
        } 
    return 0;
    }