简体   繁体   中英

C: Program won't ask the user again if the user inputs a character using fflush(stdin)

Obviously I'm not going to post my whole code here as it IS very long, it is a tax calculator after all. This problem applies to all my scanfs that need double values as input from the user. Basically as the title says, my program doesn't ask the user to input another value even if it's a character, which obviously isn't a double value so some help will be very appreciated. Forgive me as I'm still in the first year of my course and don't know everything about programming.

double salary;
printf("This program will compute your yearly and monthly witholding tax for you \n");
printf("How much is your total monthly salary? ");
fflush(stdin);
scanf("%lf", &salary);
while (salary < 0)
{
    printf("\n");
    printf("Invalid Input\n");
    printf("How much is your total monthly salary? ");
    fflush(stdin);
    scanf("%lf", &salary);
}

You correctly diagnosed the problem: invalid input stays in the input buffer, causing every subsequent scanf to fail. You cannot correct this with fflush , because it is not defined for input streams. Note that you also misuse scanf as you do not test the return value.

The simple and generic solution to your problem is this: replace calls to scanf with calls to a function that reads a line from the user and parses it as a string repeatedly until either EOF or correct input is entered.

This function takes a range for validity checking. You can pass infinities if you dont want to accept all input.

int getvalue(const char *prompt, double *vp, double low, double high) {
    char buffer[128];
    for (;;) {
        printf("%s ", prompt);
        if (!fgets(buffer, sizeof buffer, stdin)) {
            printf("EOF reached, aborting\n");
            // you can also return -1 and have the caller take appropriate action
            exit(1);
        }
        if (sscanf(buffer, "%lf", vp) == 1 && *vp >= low && *vp <= high)
            return 0;
        printf("invalid input\n");
    }
}

In your code fragment, you would replace everything with this:

double salary;
printf("This program will compute your yearly and monthly withholding tax for you\n");
getvalue("How much is your total monthly salary?", &salary, 0.0, HUGE_VAL);

HUGE_VAL is defined in <math.h> , but its value seem a bit high for a salary anyway, you can just write a decent maximum such as 1E9 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM