Check return value of scanf
and clear input buffer in case of illegal input.
Like this:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
float sales, commission, earnings;
int state;
while(true) {
printf( "Enter sales in dollars ( -1 to end ): " );
if((state = scanf("%f", &sales )) != 1){
if(state == EOF)
return 0;
printf("invalid input.\n");
while(getchar() != '\n');//clear input
continue;
}
if ( sales == -1 ) {
return 0;
} else if(sales < 0){
printf("invalid input.\nA negative value was entered.\n");
continue;
}
commission = sales / 100 * 9;
earnings = commission + 200;
printf( "Salary is %.2f\n", earnings );
}
return 0;
}
1
solved C program goes into infinite loop with scanf [duplicate]