0

I'm having trouble with the getchar() function. How do I distinguish if the user inputs a number larger than 10? I'm using int temp = value-'0'; to convert any number between 0-9 from ASCII. If you input 10 it returns 49 (ascii for 1). Help appreciated!

Animalben
  • 3
  • 2
  • 3
    The `getchar` function gets a single character. If they type `10` , that is two characters. You will need to read (at least) two characters to detect this case. – M.M Sep 12 '14 at 01:31
  • 1
    A number larger that 9 would be 2 (or more digits) and would require multiple calls to `getchar()`. You need to show some more code. – John3136 Sep 12 '14 at 01:31
  • Alright. I added more code. The reason I ask is because the assignment specifically requires getchar() to be used, aswell as handling inputs of 10. – Animalben Sep 12 '14 at 03:08

1 Answers1

3

The getchar() function only gives you a single character (or an end-of-file indicator), so you'll never get 10, you'll get 1 then 0.

If you want to input a line, look into fgets() or find a safe input function like this one.

Then you can use functions like sscanf(), atoi() or strtol() to process the line into a more suitable format, including error checking.


If you must use getchar() then it's a simple matter of maintaining an accumulator and working out the running value:

#include <stdio.h>
#include <ctype.h>

int main (void) {
    int ch, accum = 0;
    printf ("Enter your number (non-numerics will cease evaluation): ");
    while ((ch = getchar()) != EOF) {
        if (!isdigit (ch)) break;
        accum = accum * 10 + ch - '0';
        printf ("ch = %c, accum = %d\n", ch, accum);
    }
    return 0;
}

A sample run of this program follows:

Enter your number (non-numerics will cease evaluation): 314159
ch = 3, accum = 3
ch = 1, accum = 31
ch = 4, accum = 314
ch = 1, accum = 3141
ch = 5, accum = 31415
ch = 9, accum = 314159
Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953