簡體   English   中英

C:程序不會再詢問用戶是否使用fflush(stdin)輸入了字符

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

顯然,我不會在這里發布整個代碼,因為它很長,畢竟它是一個稅收計算器。 此問題適用於我所有需要double值作為用戶輸入的scanfs。 基本上如標題所述,我的程序不會要求用戶輸入另一個值,即使它是一個字符,這顯然也不是雙精度值,因此對您有所幫助。 原諒我,因為我仍處於課程的第一年,對編程一無所知。

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);
}

您已正確診斷出該問題:無效的輸入保留在輸入緩沖區中,從而導致每個后續的scanf失敗。 您無法使用fflush糾正此問題,因為它不是為輸入流定義的。 請注意,由於不測試返回值,因此也會濫用scanf

解決您的問題的簡單而通用的解決方案是:將對scanf的調用替換為對函數的調用,該函數從用戶讀取一行並將其重復解析為字符串,直到輸入EOF或正確的輸入為止。

此功能需要進行有效性檢查的范圍。 如果您不想接受所有輸入,則可以傳遞無窮大。

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");
    }
}

在代碼片段中,您將用以下內容替換所有內容:

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是在<math.h>定義的,但是對於薪水來說它的值似乎有點高,您可以編寫一個像樣的最大值,例如1E9

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM