如何检查用户在一个字符串中输入的字符序列是否正确?

问题描述 投票:0回答:1

我需要用户输入一个具有这种精确模型的参考。####.###必须有8个字符,第五个字符是句号。

目前,我把这段代码放在一个while语句中,检查字符串的长度,如果第五个字符是一个句号。

我如何检查其他字符是数字?记住,我需要用户在一个步骤中输入引用。

bool wrongRef{true};
std::string ref;
while (wrongRef)
{
    std::cout << "Enter the reference (####.###) : ";
    std::cin >> ref;
    if (ref[4] == '.' && ref.length() == 8 )
    {
        wrongRef = false;
    }
    else
        std::cout << "Wrong input. Reference should be '####.###'\n";
}

谢谢您的帮助。

c++
1个回答
1
投票

这似乎是一个很好的用例 std::regex_match. 你可以这样使用它。

std::regex r{R"(^\d{4}\.\d{3}$)"};
std::cout << "Enter the reference (####.###) : ";
std::cin >> ref;
if (std::regex_match(ref, r))
 // ...
else 
  std::cout << "Wrong input. Reference should be '####.###'\n";

这个regex的工作原理如下:

^ 匹配字符串的开头

\d{4} 四位数

\. 满分

\d{3} 再对上三位数

$ 符串尾


0
投票

有许多可能的选择。一个最简单的选项是--你可以只数数字,它应该等于 original_string.length()-1

计数位数可以像下面这样做。

int count_digits(const std::string& s)
{
    return std::count_if(s.begin(), s.end(), 
                         [](unsigned char c){ return std::isdigit(c); }
                        );
}

现在你可以把它插入到你的程序中,如下图所示。

if (ref[4] == '.' && 
    ref.length() == 8  && 
   (ref.length() -1) == count_digits(ref))
{
     //correct input
}
else
{
    //incorrect input 
}
© www.soinside.com 2019 - 2024. All rights reserved.