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!
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