/****************************************************/ /* */ /* program: "Death by scanf" */ /* file-name: death_by_scanf.c */ /* */ /* author: Jesse Bollinger */ /* date of creation: 2009-01-30 */ /* date of latest revision: 2009-02-06 */ /* */ /* description: */ /* */ /* This program provides an environment for */ /* demonstrating one of the common pitfalls */ /* of scanf, unexpected loop behavior. */ /* */ /* Type 0 at scanf prompt to quit the program. */ /* */ /****************************************************/ #include #include #define MAX_NUM_OF_LOOPS 12 int main() { int scanf_read_count; int input_value; int i; for( i = 0; i < MAX_NUM_OF_LOOPS; i++ ) { printf( "\n------------------------------------------\n" ); printf( "scanf wants a number\n" ); printf( "write your input and press enter: " ); scanf_read_count = scanf( "%d", &input_value ); if( input_value == 0 ) { break; } printf( "\nscanf has read %d value(s)\n", scanf_read_count ); printf( "input_value is %d\n", input_value ); printf( "------------------------------------------\n" ); } /* exit notification */ printf( "\n" ); /* prevent console from instantly closing on program termination */ /* by waiting for enter to be pressed */ fflush( stdin ); scanf( "%*c" ); /* EXIT_SUCCESS return code tells the OS that program execution went ok */ return EXIT_SUCCESS; }