在C ++(gcc)中有TryParse等价物吗? [英] Is there a TryParse equivalent in C++ (gcc)?

查看:163
本文介绍了在C ++(gcc)中有TryParse等价物吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++(gcc)中有相当于TryParse吗?

Is there a equivalent of TryParse in C++(gcc) ?

我想解析一个可能包含(+31321)我知道电话号码存储为字符串和字符串匹配,但为了我的需要,我想存储它们,有时它们可​​能包含加号(+)。

I would like to parse a string which may contain (+31321) and store it as long. I know phone numbers are stored as strings and string matched but for my needs , I would like to store them as long and sometimes they might contain pluses (+). What would parse it in C++?

推荐答案

strtoul()和家庭的麻烦没有真正的方法来测试失败。

如果它无法解析,则返回0,而不设置errno(仅在溢出时设置)。

The trouble with strtoul() and family there is no real way to test for failure.
If it fails to parse then it returns 0 without setting errno (which is only set on overflow).

boost词法转换

#include <boost/lexical_cast.hpp>


int main()
{
    try
    {
        long x = boost::lexical_cast<long>("+1234");
        std::cout << "X is " << x << "\n";
    }
    catch(...)
    {
        std::cout << "Failed\n";
    }
}

使用流进行操作

int main()
{
    try
    {
        std::stringstream stream("+1234");
        long x;
        char test;

        if ((!(stream >> x)) || (stream >> test))
        {
            // You should test that the stream into x worked.
            // You should also test that there is nothing left in the stream
            //    Above: if (stream >> test) is good then there was content left after the long
            //           This is an indication that the value you were parsing is not a number.
            throw std::runtime_error("Failed");
        }
        std::cout << "X is " << x << "\n";
    }
    catch(...)
    {
        std::cout << "Failed\n";
    }
}

使用scanf:

int main()
{
    try
    {
        char integer[] = "+1234";
        long x;
        int  len;

        if (sscanf(integer, "%ld%n", &x, &len) != 1 || (len != strlen(integer)))
        {
            // Check the scanf worked.
            // Also check the scanf() read everything from the string.
            // If there was anything left it indicates a failure.
            throw std::runtime_error("Failed");
        }
        std::cout << "X is " << x << "\n";
    }
    catch(...)
    {
        std::cout << "Failed\n";
    }
}

这篇关于在C ++(gcc)中有TryParse等价物吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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