【发布时间】: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