如何添加不是字母数字的字符

时间:2014-04-12 22:49:32

标签: c++

我让程序按照我想要处理的字母数字值的方式工作,但我也希望创建一个允许句点,连字符和下划线的例外。但是我想否定所有其他角色是非法的。

void AccountData::assignAccount()
{
    std::cout << "Input Account Name: ";
    std::string inputAccount;
    std::getline(std::cin, inputAccount);
    std::string useAccount = inputAccount.substr(0, 15);

    if (std::all_of(begin(useAccount), end(useAccount), std::isalnum)) varAccount = useAccount;
    else
    {
        bool valid = true;

        while (valid)
        {
            std::cout << "\nAccounts can only contain alphanumeric values with exceptions of _-.\n\nInput Account Name: ";
            std::getline(std::cin, inputAccount);
            useAccount = inputAccount.substr(0, 15);

            if (std::all_of(begin(useAccount), end(useAccount), std::isalnum))
            {
                varAccount = useAccount;
                valid = false;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以编写自己的谓词,并将其与all_of一起使用,如下所示:

bool myFun(char a)
{
    return (isalnum(a) || a=='_' || a=='-' || a=='.');
}
void AccountData::assignAccount()
{
    std::cout << "Input Account Name: ";
    std::string inputAccount;
    std::getline(std::cin, inputAccount);
    std::string useAccount = inputAccount.substr(0, 15);

    if (std::all_of(begin(useAccount), end(useAccount), myFun)) varAccount = useAccount;
    else
    {
        bool valid = true;

        while (valid)
        {
            std::cout << "\nAccounts can only contain alphanumeric values with exceptions of _-.\n\nInput Account Name: ";
            std::getline(std::cin, inputAccount);
            useAccount = inputAccount.substr(0, 15);

            if (std::all_of(begin(useAccount), end(useAccount), myFun))
            {
                varAccount = useAccount;
                valid = false;
            }
        }
    }
}