errors/input-1.c - Læsning af double og input med input validering. | Lektion 7 - slide 8 : 25 Program 1 |
#include <stdio.h> #include <stdlib.h> void clear_standard_input_line(void); void get_double_int_input(void); int main(void) { get_double_int_input(); return 0; } void get_double_int_input(void) { double x = 0.0; int i = 0, input_result; // Prompting for input of a double and an int: printf("Enter a double and an integer:\n"); input_result = scanf("%lf %d", &x, &i); // Handling of erroneous input - a non-controllable mess if (input_result == 0){ // double and int reading both unsuccessful. clear_standard_input_line(); // Prompt for both numbers again. printf("Serious now: Enter a double and an integer:\n"); scanf("%lf %d", &x, &i); } else if (input_result == 1){ // int reading unsuccessful. clear_standard_input_line(); // Prompt for the integer again: printf("Serious now: Enter the missing integer:\n"); input_result = scanf("%d", &i); } else if (input_result != 2){ printf("Input of double and int. Should not happen. Bye"); exit(EXIT_FAILURE); } else if (input_result == 2){ clear_standard_input_line(); /* Clear rest of line */ } // We hope for the postcondition: input_result == 2 // Proceed - input hopefully OK ?! printf("x = %f, i = %d\n", x, i); } void clear_standard_input_line(void){ int ch; while ((ch = getchar()) != '\n' && ch != EOF); }