C ++:使用多种条件验证字符串

时间:2019-05-03 03:10:12

标签: c++ string validation

我正在尝试为遵循以下准则的字符串编写验证:

  1. 可以是字母

  2. 可以是“。”或','

  3. 可以有一个空格

  4. 不能为空

例如,“ Bob”,“ Bob Smith”和“ Bob Smith,Jr.”应该没问题,而“”或只是按Enter键就没问题。

如果字符串遵循这些准则,则该函数应简单地将其返回,否则,它将继续循环直至输入正确的条目。

我尝试了几种不同的循环方法来进行验证,如果我正确地理解了破解方法,我相信该结构应该可以工作。 也就是说,输入“ Bob”之类的简单字符串会使测试失败。我也不确定如何确保用户不能只是按空格键或按Enter键。

std::string patronName()
    {
        std::string name;
        bool loopFlag = true;

        do
        {
            std::cout << "Please enter the name of the Patron: ";
            std::getline(std::cin, name);

            for (int i = 0; i < name.length(); i++)
            {
                if (!isalpha(name[i]) || !ispunct(name[i]) || !isspace(name[i]) || name.empty())
                {
                    std::cout << "Invalid name entry." << std::endl;
                    break; //If we're invalid, doesn't matter what the rest is
                }
                loopFlag = false;
            }

        }
        while(loopFlag);

        return name;
    }

我的逻辑中是否缺少任何明显的错误?

1 个答案:

答案 0 :(得分:3)

如果char不是一个alpha字符,或者它不是操纵或指定词,那么它无效。

字母c不是空格,因此符合您的条件。

尝试使用&&而不是||。如果char不是字母,并且不是操纵力,也不是空格,则无效。

我会考虑重构您的代码,以将验证与其他代码分开。

bool isValid(const std::string& str)
{
    // Assume the string is valid - up to us to prove it is not...
    bool result = true;
    // Assume the stringis all spaces - up to us to mark when we see a valid non whitespace
    bool allSpaces = true;

    size_t len = str.length();
    for(size_t i = 0; i < len; i++)
    {
        unsigned char ch = (unsigned char)str[i];
        // alpha and punctuation are ok and mean that the string has
        // something other than a space.
        if (isalpha(ch) || ispunct(ch))
        {
          allSpaces = false;
          continue;
        }
        // space is ok - as long as we have something else too...
        if (isspace(ch))
        {
            continue;
        }
        // not a space, allowed punctuation or an alpha ?
        // must be an error!
        result = false;
        break;
    }
    if (allSpaces)
    {
        result = false;
    }
    return result;
}

请参阅This answer,以获取有关为什么建议强制转换为未签名字符的信息。