簡體   English   中英

在C語言中,我如何只接受某些字符串並繼續要求用戶輸入,直到輸入了有效的輸入?

[英]In C, how do I only accept certain strings and continue to ask the user for input until valid input is entered?

我試圖用C語言編寫一個簡單的程序,該程序接受一個字符串並根據該輸入執行操作。 但是,如果用戶輸入了無效的字符串,我希望程序再次要求用戶輸入,直到用戶提供有效的輸入字符串為止。

輸出示例:

P: Please enter a string.
U: runMarathon
P: Unable to process request, please enter a valid Input:
U: rideBike
P: Unable to process request, please enter a valid Input:
U: sayHello
P: Hello World.

我有一個像這樣的程序:

int num;

while (scanf("%d",&num) != 1 || num <= 0)
{
    printf("Please enter an integer greater than 0\n");
    fflush(stdin);
}

該程序似乎有效; 但是我有一個經驗豐富的C開發人員告訴我,永遠不要使用fflush(stdin)。

這是我到目前為止的內容:

int main()
{
    char input[];
    while (scanf("Please enter a command: %s\n",input))
    {
        printf("Your command is this: %s\n",input);
    }
}

但是,當運行此方法時,在接受輸入后,程序將連續打印:

Your command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: Hello

等等,令我感到驚訝的是,我無法為看似簡單的問題找到任何資源。 我知道我可以使用strcmp比較字符串,但是如何使while循環等待用戶輸入,然后再次打印出響應? 為什么不能使用fflush(stdin)?

任何輸入表示贊賞,謝謝!

意外輸入的問題在於scanf不會從輸入緩沖區中刪除該輸入,因此,下一次循環迭代時,它將嘗試讀取相同的意外輸入。

解決此問題的最常見方法是使用fgets讀取整行,然后在字符串上使用sscanf

為什么不能使用fflush(stdin)

從技術上講,您可以做到這一點,但您必須非常小心,因為fflush僅由C標准定義用於輸出/更新流,而不是用於輸入流,因此fflush(stdin)的行為是undefined 然后,某些實現方式可能是例如清除輸入緩沖區。 如果您真的有迫切需要使用它,請查閱實現的文檔和代碼。


C-99標准§7.19.5.2/2/3 fflush函數

概要

1 #include <stdio.h> int fflush(FILE *stream);

2如果流指向未輸入最新操作的輸出流或更新流,則fflush函數會使該流的所有未寫入數據都將傳遞到主機環境中,並寫入該文件中; 否則,行為是不確定的。

3如果stream是空指針,則fflush函數對上面定義了行為的所有流執行此刷新動作。

退貨

4 fflush函數設置流的錯誤指示符,如果發生寫錯誤,則返回EOF,否則返回零。

您可以執行以下操作:

int main()
{
    char input[50];
    do
    {
        printf("Please enter a command:");
        if (scanf("%s", &input) != 1) //scanf returns the number of args successfully received
        {
            printf("Please enter a command\n");
        }

        printf("Please enter a valid command!\n");

    } while (strcmp(input, "good") != 0); //repeat above until input = "good"

                                          //print the good command
    printf("Your command is this: %s\n", input);
    return 0;
}

需要注意的一點是,您應始終確保要寫入的緩沖區足夠大以容納正在放入的緩沖區。

暫無
暫無

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

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