/* * read_nums.c * * Functions to read numbers with input error detection. * * Started by: S. A. Norman * * Completed by: * Lab section: * Date: */ #include #include int read_int(void); /* * REQUIRES * User has been prompted to type in an int. * PROMISES * If an int can be read from the standard input stream, that * int is the return value. If not, an error message is printed * and exit is called with an argument of 1. */ double read_double(void); /* * REQUIRES * User has been prompted to type in a double. * PROMISES * If a double can be read from the standard input stream, that * double is the return value. If not, an error message is printed * and exit is called with an argument of 1. */ int main(void) { int the_int; double the_double; printf("Doing tests of read_int and read_double functions ...\n\n"); printf("Please try to enter an int: "); the_int = read_int(); printf("read_int succeeded. It read a value of %d.\n", the_int); printf("Please try to enter an double: "); the_double = read_double(); printf("read_double succeeded. It read a value of %g.\n", the_double); return 0; } read_int(void) { int nscan; int a; nscan=scanf("%d",&a); if (nscan != 1) { printf("Your input is not an integer. Program will terminate.\n"); exit(1); } else return a; } read_double(void) { double b; int nscan; nscan = scanf("%lf",&b); if (nscan !=1) { printf("Your input is not a double. Program will terminate."); exit(1); } else return b; }