簡體   English   中英

驗證數組C ++中的輸入數據

[英]Validate input data in an array C++

我有從以下網址取出的程序: https : //intcpp.tech-academy.co.uk/input-validation/並且工作正常,我做了一些更改,因為我需要該程序不斷要求用戶輸入一個有效的輸入,所以為什么它在其中有一段時間,但是它僅在第4次輸入之后才詢問4次,輸入是否有效,是否正確就無所謂,有誰知道我可以解決這個問題。 謝謝

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main () {

    cout << "Please enter name:" << endl;
    string userName;
    getline(cin, userName);

    bool rejected = false;

    while (rejected == false)
    {
        for (unsigned int i = 0; i < userName.length() && !rejected; i++)
        {

            if (isalpha(userName[i]))
                continue;

            else if (userName[i] == ' ')
                continue;

            else
            {
                cout << "Error, Please enter Patient's name again, First Name: ";
                getline(cin, userName);
                rejected = false;
            }

        }
        rejected = true;
    }

    system("pause");
    return 0;
}

我個人會做類似的事情

bool is_valid_username(std::string const& username)
{
    // First trim the string of all leading and trailing white-space
    trim(username);

    if (username.length() == 0)
        return false;  // Input was empty or all spaces

    return std::all_of(begin(username), end(username), [](char const ch)
    {
        return std::isalpha(ch) || ch == ' '; // Only letters and spaces are allowed
    });
}

std::string get_username()
{
    std::string username;

    do
    {
        std::cout << "Please enter username: ";
        std::getline(std::cin, username);
    } while (!is_valid_username(username));

    return username;
}

[有關trim功能,請參見此舊答案 ]

如果輸入為空,所有空格或包含非字母或非空格,則get_username函數將繼續永遠詢問用戶名。

這是std::all_of的參考

這是有關lambda表達式的參考

    if (isalpha(userName[i]) || (userName[i] == ' '))
        continue;
    else
    {
        cout << "Error, Please enter Patient's name again, First Name: ";
        getline(cin, userName);
        i = -1; //Reset check name
    }

試試吧! 將unsigned int更改為int

暫無
暫無

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

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