簡體   English   中英

如何在 C++ 中限制用戶輸入字符串和字符?

[英]How to limit user input in C++ for strings & characters?

我正在嘗試創建一個小型餐廳程序,我將在其中練習到目前為止我在 C++ 中學到的所有內容。 但是我跳進了一個小問題。 在程序開始時,我提示用戶是否要進入程序,或者選擇Y或N退出程序。如果輸入的不是其他任何內容,程序會告訴用戶無效。

問題是假設用戶輸入了一個無效字符 a。 無效的 output 將正常顯示,一切看起來都很完美。 但如果用戶輸入兩個或更多字符,則無效的 output 案例將被打印與用戶輸入的字符一樣多。 下面的示例:

Output 圖像

#include <iostream>

int main()
{
    char ContinueAnswer;
    std::string Employee {"Lara"};
    std::cout << "\n\t\t\t---------------------------------------"
              << "\n\t\t\t|                                     |"    
              << "\n\t\t\t|            Welcome to OP            |"
              << "\n\t\t\t|Home to the best fast food in Orlando|"
              << "\n\t\t\t|                                     |"
              << "\n\t\t\t--------------------------------------|" << std::endl;

do
{
    std::cout << "\n\t\t\t    Would you like to enter? (Y/N)"
              << "\n\t\t\t                  "; std::cin >> ContinueAnswer;
    if(ContinueAnswer == 'y' || ContinueAnswer == 'Y')
    {
        system("cls");
        std::cout << "\n\t\t\t              My name is " << Employee << "."
                  << "\n\t\t\tI will assist you as we go through the menu." << std::endl;
    }
    else if(ContinueAnswer == 'n' || ContinueAnswer == 'N')
    {
        std::cout << "\t\t\t\tGoodbye and come again!" << std::endl;
        return 0;
    }
    else
        std::cout << "\n\t\t\t\t  Invalid Response" << std::endl;
}
while(ContinueAnswer != 'y' && ContinueAnswer != 'Y')

感謝您花時間閱讀並感謝任何回答的人:)

您可以簡單地讓用戶輸入一個string

std::string ContinueAnswer;

並像這樣比較:

if(ContinueAnswer == "y" || ContinueAnswer == "Y")

它將處理多字符輸入。

如果您還想處理輸入中的空格,請更改:

std::cin >> ContinueAnswer;

至:

std::getline(std::cin, ContinueAnswer);

在解決您的問題之前,我需要指出,在對輸入進行任何操作之前,您應該始終驗證輸入是否成功。 由於 inout 失敗而未設置的處理變量是一個相當常見的錯誤來源。 例如:

if (std::cin >> ContinueAnswer) {
    // do something with successfully read data
}
else {
    // deal with the input failing, e.g., bail out
}

如果讀取了九個預期字符,我假設您認為同一行上的所有內容都是無效的。 可以將一行讀入std::string 但是,這可能會被濫用以提供極長的輸入行,最終會使您的程序崩潰。 此外,將數據讀入std::string只是為了將其丟棄似乎是不明智的。 我建議忽略所有字符,包括可以使用的換行符(您需要包含<limits>用於這種方法):

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ‘\n’);

第一個參數是一個特殊值,表示在換行符之前可以有任意數量的字符。 在實踐中,您可能可以使用像 1000 這樣的值,這很好,但它可以被玩弄。 當然,在實際應用中,可以使用專用限制來防止對手長時間保持程序繁忙。 我傾向於假設我的程序受到攻擊,以確保我處理不尋常的情況。

快速重構會產生以下結果:

#include <iostream>
#include <cstring>
#include <stdio.h>

int main()
{
        char ContinueAnswer[256];
        std::string Employee {"Lara"};
        std::cout << "\n\t\t\t---------------------------------------"
              << "\n\t\t\t|                                     |"
              << "\n\t\t\t|            Welcome to OP            |"
              << "\n\t\t\t|Home to the best fast food in Orlando|"
              << "\n\t\t\t|                                     |"
              << "\n\t\t\t--------------------------------------|" << std::endl;

        do
        {
            std::cout << "\n\t\t\t    Would you like to enter? (Y/N)"
                      << "\n\t\t\t                  "; std::cin.getline(ContinueAnswer,sizeof(ContinueAnswer));
            if(strcmp(ContinueAnswer, "Y") == 0 || strcmp(ContinueAnswer, "y") == 0)
            {
                system("cls");
                std::cout << "\n\t\t\t              My name is " << Employee << "."
                          << "\n\t\t\tI will assist you as we go through the menu." << std::endl;
            }
            else if(strcmp(ContinueAnswer, "N") == 0 || strcmp(ContinueAnswer, "n") == 0)
            {
                std::cout << "\t\t\t\tGoodbye and come again!" << std::endl;
                return 0;
            }
            else
                std::cout << "\n\t\t\t\t  Invalid Response" << std::endl; 
        }       
        while(true);
}

cin.getline 將獲取所有字符,直到一個分隔符。 然后,您可以使用 strcmp 檢查等效性並拒絕除您想要的以外的任何內容。 最后,您似乎希望它處於無限循環中,所以不要擔心最后檢查輸入並返回。

暫無
暫無

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

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