>This is a very weird case and it only happeneds to me in visual c++ 6.0
This is a common and predictable problem with scanf. The reason it occurs is because if scanf fails to convert input it leaves it in the buffer. The next iteration of the loop reads the same invalid input and an infinite loop is created. The best solution is to avoid scanf, but you asked for the simplest, so you can write a function to clean up the mess in the input stream. It's also a good practice to check the return value of scanf just to be safe:
Code:
#include <stdio.h>
static void discard ( FILE *in )
{
int c;
while ( ( c = fgetc ( in ) ) != '\n' && c != EOF )
;
}
int main ( void )
{
int number;
do {
if ( scanf ( "%d", &number ) != 1 || number < 1 || 5 < number ) {
/* Clean up */
discard ( stdin );
printf ( "Your number is out of range\n" );
}
} while ( number < 1 || 5 < number );
printf ( "Your number was %d\n", number );
return 0;
}
-Prelude