如何验证字符串是否有效(即使它有一个点)?

Mic*_*ver 10 c++ string double

我一直在寻找一种方法来确定我的字符串值是否是一个有效的双倍,而我还没有找到一种方法也不会拒绝一个带有一个点的数字...

在我的搜索中,我找到了这个

如何确定字符串是否是带C++的数字?

而Charles Salvia给出的答案是

bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
Run Code Online (Sandbox Code Playgroud)

这适用于任何没有点的数字,但有点的数字会被拒绝...

eml*_*lai 12

你可能会std::stod喜欢这样使用:

bool is_number(const std::string& s)
{
    try
    {
        std::stod(s);
    }
    catch(...)
    {
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

但这可能效率很低,例如零成本例外.

所以使用@ Robinson的解决方案或者strtod是更好的选择:

bool is_number(const std::string& s)
{
    char* end = 0;
    double val = strtod(s.c_str(), &end);
    return end != s.c_str() && *end == '\0' && val != HUGE_VAL;
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*son 5

为什么不直接使用 istringstream?

#include <sstream>

bool is_numeric (std::string const & str) 
{
    auto result = double();
    auto i = std::istringstream(str);

    i >> result;      

    return !i.fail() && i.eof();
}
Run Code Online (Sandbox Code Playgroud)


fon*_*onx 2

您还可以计算字符串包含多少个点。如果该数字小于或等于 1 并且所有其他字符都是数字,则您的字符串是有效的双精度值。

bool isnumber(const string& s)
{
    int nb_point=0;
    for (int i=0; i<s.length();i++)
    {
         if (s[i]=='.')
         {
              nb_point++;
         }
         else if (!isdigit(s[i])
         {
              return false;
         }
    }
    if (nb_point<=1)
    {
          return true;
    }
    else
    {
          return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您知道如何处理,您也可以使用正则表达式......