【问题标题】:What's the fastest way to check if a string is a number?检查字符串是否为数字的最快方法是什么?
【发布时间】:2012-12-06 11:34:27
【问题描述】:

检查“2.4393”或“2”之类的字符串是否有效的最快方法是什么?它们都可以用双精度表示,而字符串“2.343”。还是“ab.34”不是?特别是,我希望能够读取任何字符串,如果它 can 是双精度,则为其分配一个双精度变量,如果它不能是双精度(如果它是一个单词或只是无效输入),将显示一条错误消息。

【问题讨论】:

  • 你的输入编码是什么?简单的 ASCII 还是别的什么?
  • stackoverflow.com/questions/392981/… 可能会有所帮助。
  • 将其放入流中(例如std::stringstream)并执行if ( !(stream >> mydouble) ) { myError(); }
  • @stefan:那不接受“3z”或“1.1”之类的东西吗?
  • @j_random_hacker:"2 " 呢?该问题没有说明它是否有效,下面的答案认为它无效,但您的代码认为它有效,因为它跳过了空格然后无法读取字符。

标签: c++


【解决方案1】:

使用std::istringstream 并确认使用eof() 消耗了所有数据:

std::istringstream in("123.34ab");
double val;
if (in >> val && in.eof())
{
    // Valid, with no trailing data.
}
else
{
    // Invalid.
}

http://ideone.com/gpPvu8查看演示。

【讨论】:

  • in.eof() 也可以,不是吗? (这会让它更“C++ 时尚”@billybob)
【解决方案2】:

您可以使用std::stod()。如果字符串不能转换,则抛出异常。

【讨论】:

    【解决方案3】:

    正如stefan所说,你可以使用std::istringstream

    coords          getWinSize(const std::string& s1, const std::string& s2)
    {
      coords winSize;
      std::istringstream iss1(s1);
      std::istringstream iss2(s2);
    
      if ((iss1 >> winSize.x).fail())
        throw blabla_exception(__FUNCTION__, __LINE__, "Invalid width value");
      /*
       .....
      */
    }
    

    在我的代码中,坐标是:

    typedef struct coords {
        int     x;
        int     y;
    } coords;
    

    【讨论】:

    • 它不会检查“123.45ab”
    【解决方案4】:

    使用boost::lexical_cast,如果转换失败则抛出异常。

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 1970-01-01
      • 2014-12-14
      • 2021-10-11
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2013-07-06
      相关资源
      最近更新 更多