是否有stl或boost函数来确定字符串是否为数字?

Inn*_*nno 11 c++ boost stl

我对C++,提升等很陌生.

我想知道在boost或STL中是否已有函数我可以用来确定字符串是否为数字.

数字字符串可能如下所示:100

要么

100.52

我知道有很多例子如何编写这样的函数,但我想知道是否已经有一个我可以使用的函数.

我正在寻找一个纯C++ - 解决方案,而不是C.

[更新:我已经使用lexical_cast来转换我的字符串了,我只是想知道是否有像is_numeric这样的方法可以用于此...]

Mat*_*tis 10

不,没有现成的方法直接这样做.

您可以使用boost::lexical_cast<double>(your_string),如果它抛出异常,那么您的字符串不是双精度型.

    bool is_a_number = false;
    try
    {
        lexical_cast<double>(your_string);
        is_a_number = true;
    }
    catch(bad_lexical_cast &)
    {
        // if it throws, it's not a number.
    }
Run Code Online (Sandbox Code Playgroud)

  • 这是一个快速的解决方案.这样做有相当大的开销(副本+字符串流+异常),这种东西经常用在循环中.此外,异常法西斯分子会告诉您,您正在使用流量控制的例外而不是特殊情况. (4认同)

Jam*_*nze 9

boost::regex(或者std::regex,如果你有C++ 0x)可以使用; 你可以定义你想接受的内容(例如在你的上下文中,"0x12E"是一个数字还是不是?).对于C++整数:

"\\s*[+-]?([1-9][0-9]*|0[0-7]*|0[xX][0-9a-fA-F]+)"
Run Code Online (Sandbox Code Playgroud)

对于C++浮点:

"\\s*[+-]?([0-9]+\\.[0-9]*([Ee][+-]?[0-9]+)?|\\.[0-9]+([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)"
Run Code Online (Sandbox Code Playgroud)

但是,根据你正在做的事情,你可能不需要支持复杂的事情.你引用的两个例子将被涵盖

"[0-9]+(\\.[0-9]*)?"
Run Code Online (Sandbox Code Playgroud)

例如.

如果您稍后需要数值,也可以将字符串转换为a istringstream,并立即进行转换.如果没有错误,并且您提取了所有字符,则该字符串是一个数字; 如果不是,那不是.但是,这样可以减少对要接受的确切格式的控制.


ild*_*arn 6

如果性能是一个问题,在所有的,我会用升压.精神.而不是std::stringstream:

#include <string>
#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>

bool is_numeric(std::string const& str)
{
    std::string::const_iterator first(str.begin()), last(str.end());
    return boost::spirit::qi::parse(first, last, boost::spirit::double_)
        && first == last;
}
Run Code Online (Sandbox Code Playgroud)

如果要允许尾随空格,请执行以下操作:

#include <string>
#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_char_class.hpp>
#include <boost/spirit/include/qi_operator.hpp>

bool is_numeric(std::string const& str)
{
    std::string::const_iterator first(str.begin()), last(str.end());
    return boost::spirit::qi::parse(first, last,
            boost::spirit::double_ >> *boost::spirit::qi::space)
        && first == last;
}
Run Code Online (Sandbox Code Playgroud)