簡體   English   中英

如何驗證用戶是否輸入了字符以外的任何內容?

[英]How do validate if user inputs anything other than a character?

我有一個功能,詢問用戶是否要返回主菜單。

void menuReturn() {
    char cont;
    do {
        cout << "Return to Main Menu? [Y/N]: ";
        cin >> cont;
        cont = toupper(cont);
        if (cont == 'Y') {
            system("cls");
            break;
        }
        else if (cont == 'N') { 
            cout << "Closing program...";
            exit(0);    
        }
        else {
            cout << "Invalid choice" << endl;
        }        
    } while (cont !=  'Y'|| cont != 'N');
}

但是當用戶輸入一個字符串或一個大於九 (9) 的整數時,控制台會顯示:

Return to Main Menu? [Y/N]: apple
Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: 

如何擺脫多余的返回菜單消息? 我該如何讓它看起來像這樣?

Return to Main Menu? [Y/N]: apple
Invalid choice
Return to Main Menu? [Y/N]:

將輸入作為字符串收集,然后使用 string.length() 檢查它是否只有一個字符,如果是一個字符,則將其轉換為 char。 您可以使用 strcopy 方法或僅轉換它

char character = string[0];

我不確定上面的方法是否有效,但請嘗試一下。 希望有幫助! 如果您想在控制台中輸入空格,也可以使用std::getline(std::cin, string)而不是 std::cin !

這里發生的事情是char只能容納一個字符,而apple占用了 5 個字符。

在循環的每次迭代中, std::cin一次僅從控制台讀取 1 個字符(您已經輸入)。 將打印語句std::cout << "Read: " << cont; 通過以下輸出說明了這一點:

Return to Main Menu? [Y/N] apple
Read: a
Return to Main Menu? [Y/N] Read: pInvalid Choice
Return to Main Menu? [Y/N] Read: pInvalid Choice
Return to Main Menu? [Y/N] Read: lInvalid Choice
Return to Main Menu? [Y/N] Read: eInvalid Choice

要解決此問題,請使用std::stringstd::getline ,並確保驗證輸入的長度為 1。

暫無
暫無

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

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