【问题标题】:How can I validate if string is numeric and/or one character "." is allowed如何验证字符串是否为数字和/或一个字符“。”被允许
【发布时间】:2014-12-09 18:28:44
【问题描述】:

我正在尝试验证字符串是否具有数字。我想查看字符串是否包含不允许的字符或更多字符,例如不是数字和/或一个字符“。”

我的代码是

//this code is call function (is_number). sTempArray[3] is amount such as $00.00
if(!is_number(sTempArray[3]))
{
    cout << "Your amount have letter(s) are not allowed!;
}

//the is_number is function and will run if anyone call this function.
bool MyThread::is_number(const string& data)
{
    string::const_iterator it = data.begin();
    while (it != data.end() && std::isdigit(*it))
    {
        ++it;
    }
    return !data.empty() && it == data.end();
}

我想验证字符串是否被允许。例如,字符串有一个值,它是 500.00,它会被允许,但总是被拒绝,因为字符串中有句点字符。再比如,string有一个值,是500.00a,应该是不允许的。

【问题讨论】:

  • 字符串有一个值,它是 500.00 并且 它会被允许,但它总是被拒绝因为句点字符在字符串中 - 我不知道不明白你的意思。这是一个有效的字符串吗?能否请您发布一些示例字符串并清楚地指出每个字符串是有效还是无效?
  • 你可以使用strtod并测试结束指针(如果你的数字格式和strtod中使用的格式相同的话)
  • 抱歉混淆了。如果 sTempArray[3] 有值。值为“500.00”。 is_number 函数将识别诸如“.”之类的字符。并将其作为无效返回。它应该是有效的,因为“。”应该是允许的。另一个例子,如果 sTempArray[3] 有值并且它是“50a0.00”。 is_number 函数将识别两个字符,例如“a”和“.”。并将它们作为无效返回。但是,“a”是无效的,“.”是无效的。无效但它应该是有效/允许的
  • @Daniel "If sTempArray[3] have value. The value is –" 仍然很混乱。您能否按照@Praetorian 的要求提供具体示例?也可以考虑使用std::stod

标签: c++ string iterator numeric


【解决方案1】:

在 is_number 函数的 while 循环中,您可以添加 if 语句来检查当前迭代是否为数字或检查是否为“。”在其中(也许添加一个布尔值来检查是否只有一个“。”?)。

看起来像这样:

bool MyThread::is_number(const string& data)
{
    string::const_iterator it = data.begin();
    while (it != data.end())
    {
        if (std::isdigit(*it) || it == "."){
          ++it;
        }

    }
    return !data.empty() && it == data.end();
}

【讨论】:

    【解决方案2】:

    如果点和数字已经满足,您可以添加一个布尔标志并修改循环:

    bool MyThread::is_number(const string& data)
    {
        bool dot_met = false, digit_met = false;
        for( string::const_iterator it = data.begin(); it != data.end(); ++it )
        {
            if( is_digit( *it ) ) {
                digit_met = true;
                continue;
            }
            if( *it == '.' ) {
               if( !digit_met || dot_met ) return false;
               dot_met = true;
               continue;
            }
            return false;
        }
        return digit_met;
    }
    

    此表单中的函数不接受以 . 开头的数字。 (如 .05 )如果你确实想要,改变是微不足道的。或者,您可以使用带有"\\d+\\.?\\d*" 表达式的正则表达式库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 2022-11-12
      • 2022-08-21
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多