c ++ integer-> std :: string转换。简单功能? [英] c++ integer->std::string conversion. Simple function?

查看:134
本文介绍了c ++ integer-> std :: string转换。简单功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我有一个整数;此整数需要转换为stl :: string类型。

Problem: I have an integer; this integer needs to be converted to a stl::string type.

在过去,我使用 stringstream 进行转换,这只是一种繁琐。我知道C方法是做一个 sprintf ,但我宁愿做一个类型安全(er)的C ++方法。

In the past, I've used stringstream to do a conversion, and that's just kind of cumbersome. I know the C way is to do a sprintf, but I'd much rather do a C++ method that is typesafe(er).

有更好的方法吗?

以下是我过去使用的stringstream方法:

Here is the stringstream approach I have used in the past:

std::string intToString(int i)
{
    std::stringstream ss;
    std::string s;
    ss << i;
    s = ss.str();

    return s;
}

当然,这可以改写为:

template<class T>
std::string t_to_string(T i)
{
    std::stringstream ss;
    std::string s;
    ss << i;
    s = ss.str();

    return s;
}

但是,我认为这是一个相当

However, I have the notion that this is a fairly 'heavy-weight' implementation.

Zan注意到调用是相当不错的:

Zan noted that the invocation is pretty nice, however:

std::string s = t_to_string(my_integer);

无论如何,一个更好的方式是...很好。

At any rate, a nicer way would be... nice.


相关:



替换itoa()将整数转换为字符串C ++?


推荐答案

现在在c ++ 11中,我们有

Now in c++11 we have

#include <string>
string s = std::to_string(123);

链接到引用: http://en.cppreference.com/w/cpp/string/basic_string/to_string

这篇关于c ++ integer-&gt; std :: string转换。简单功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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