It was once a bad headache for me. The C code like this:
Code:
while (gross != -1) {
printf("input: ");
scanf("%f", &gross);
}
When the code is compiled and executed, if input characters such as a, b, c, d...
It'll become an infinite loop printing "input:". But yesterday, I found a
solution to this all by chance. That is, change the code as follows:
Code:
while (gross != -1) {
printf("input: ");
scanf("%f", &gross);
getchar(); /* Add getchar() here */
}
After adding 'getchar()' into the program, the infinite loop problem is solved.
But I don't know why. Could you please tell me? And please tell me if there are
other solutions to it. Thanks a lot.
I also noticed that if any character is inputed, getchar() gets the
character. If number is inputed, getchar() gets '\n'.
I took advantage of this and wrote a small program, here is the code. Could
you please give me some advice about my code? Thanks.
Code:
#include<stdio.h>
#define BASE_PAY 200
#define salary_cal(x) 9*(x)/100 + BASE_PAY
int main()
{
float gross = 0.0;
char flag;
while ( 1 ) {
printf("Enter sales in dollars ( q to end ): ");
scanf("%f", &gross);
if ( ( flag = getchar() ) != '\n' ) { /* If character is inputed */
if ( flag == 'q' || flag == 'Q') { /* If 'q' or 'Q' is inputed, exit. */
printf("Thanks for using our product!\n");
return 0;
}
/* If the inputed character is not 'q' or 'Q' */
printf("Invalid input!\n");
continue;
}
printf("Salary: %.2f\n", salary_cal(gross) );
}
return 0;
}