/* solution-4.c demonstrates the following: - reading individual characters from stdin - converting the ASCII character code of a digit key to it numberic value - i.e. converting '5' to 5. - the loop models Horner's method of evaluating a polynomial */ #include #include #include int main( ) { int number=0; printf("\nYou will be repeatedly prompted for a single digt key and a RETURN.\n As soon as you enter a non digit character the loop will terminate\n\n"); do { char digit; /* declare it in here since its not needed outside */ printf("> "); fflush(stdout); scanf("%c", &digit ); /* OR - could have used digit = getc(stdin) */ getchar(); /* to eat the RETURN from the stdin buffer */ if (digit < '0' || digit>'9') break; /* OR - could have used isdigit(digit) */ number *= 10; number += digit-'0'; /* digit-'0' converts character '5' to number 5 */ printf("number: %d\n",number ); } while ( 1 ); /* nfinte loop - we must break out */ printf("\nFinal value of number: %d\n", number ); return 0; } /* END MAIN */