是否有stl或boost函数来确定字符串是否是数字? [英] Is there a stl or boost function to determine if a string is numeric?

查看:954
本文介绍了是否有stl或boost函数来确定字符串是否是数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++,boost等非常新。



我想知道如果boost或STL中已经有一个函数,我可以使用来确定是否

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





100.52



我知道有很多例子如何写这样的函数,但我想知道如果有已经是我可以使用的函数。



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



[更新:
我已经在使用lexical_cast转换我的字符串,我只是想知道是否有一个方法像is_numeric我可以使用...]

解决方案

不,没有现成的方式直接这样做。



code> 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&)
{
//如果它抛出,它不是一个数字。
}


I'm very new to C++, boost etc.

I would like to know if there is already a function in boost or STL I can use to determine if a string is numeric.

Numeric strings may look like: 100

or

100.52

I know there are tons of examples how to write such a function but I would like to know if there is already a function I can use for this.

I'm looking for a pure C++-solution, not C.

[UPDATE: I'm already using lexical_cast to convert my strings, I'm just wondering if there is a method like is_numeric I can use for this...]

解决方案

No, there's not a ready-made way to do this directly.

You could use boost::lexical_cast<double>(your_string) and if it throws an exception then your string is not a double.

    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.
    }

这篇关于是否有stl或boost函数来确定字符串是否是数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆