簡體   English   中英

當用戶輸入字符而不是數字時 C 中的無限循環

[英]infinite loop in C when the user enters a character instead of a number

我有一個問題,我想讓用戶輸入一個從 1.00 到 10.00 的數字,如果他輸入的數字超出該范圍,我會顯示他錯了,然后再試一次。 我認為我做得很好,但問題是如果用戶輸入一個字母循環無限重復,我會很感激你的幫助。 謝謝你。 :)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    float a;

    do
    {
        printf("Insert number between 1.00 and 10.00:\n");
        scanf("%f", &a);

        if (a < 1.00 || a > 10.0)
        {
            printf("Insert a correct number.\n");
        }
    } while (a < 1.00 || a > 10.00);

    system("pause");
    return 0;
}

當您嘗試在無效輸入上運行scanf()時,它不會更新a因為這是不可能的,因此您的循環將永遠繼續,因為a永遠不會更新並且scanf function 將永遠失敗,實際上沒有任何內容被scanf “讀取”,並且永遠不會通過無效輸入。

確保在重復循環之前通過“消耗”它們來處理無效輸入。

scanf 在輸入 stream 中留下 '\n' 字符,因此您需要跳過它:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    float a;

    do
    {
        printf("Insert number between 1.00 and 10.00:\n");
        scanf(" %f", &a);

        if (a < 1.00 || a > 10.0)
        {
            printf("Insert a correct number.\n");
        }
    } while (a < 1.00 || a > 10.00);

    printf("\nyou have entered: %f\n", a);

    return 0;
}

https://godbolt.org/z/baPxdn .但是並沒有解決輸入錯誤的問題。

我個人更喜歡閱讀該行然后掃描它(它確實解決了所有問題):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    char str[100];
    float a;

    do
    {
        printf("Insert number between 1.00 and 10.00:\n");
        fgets(str, 100, stdin);
        if(sscanf(str, " %f", &a) != 1) continue;

        if (a < 1.00 || a > 10.0)
        {
            printf("Insert a correct number.\n");
        }
    } while (a < 1.00 || a > 10.00);

    printf("\nyou have entered: %f\n", a);

    return 0;
}

https://godbolt.org/z/vxY7To

一旦發生錯誤,您必須檢查“scanf”的結果,並“清理”IO stream 緩沖區。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define CLEAN_STD_STREAM() \
 do{\
   int ch; \
   while ((ch = getchar()) != '\n' && ch != EOF); \
 }while(0)

int main()
{
    float a;

    do
    {
        printf("Insert number between 1.00 and 10.00:\n");
        if(scanf("%f", &a) != 1)
        {
          CLEAN_STD_STREAM();//fflush() dosen't work on the Linux
          continue;
        }

        if (a < 1.00 || a > 10.0)
        {
            printf("Insert a correct number.\n");
        }
    } while (a < 1.00 || a > 10.00);

    system("pause");
    return 0;
}

暫無
暫無

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

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