验证数组C ++中的输入数据

时间:2018-11-15 02:06:21

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

我个人会做类似的事情

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函数,请see this old answer]

如果输入为空,所有空格或包含非字母或非空格,get_username函数将继续永远询问用户名。

Here's a reference for std::all_of

Here's a reference about lambda expressions

答案 1 :(得分:0)

    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