c ++ integer

编程入门 行业动态 更新时间:2024-10-11 07:25:44
c ++ integer-> std :: string转换。(c++ integer->std::string conversion. Simple function?)

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

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

有更好的方法吗?

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

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

不过,我认为这是一个相当“重的”实施。

赞颂指出,调用是相当不错的,但是:

std::string s = t_to_string(my_integer);

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

有关:

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

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

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

Is there a better way to do this?

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

Of course, this could be rewritten as so:

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

Related:

Alternative to itoa() for converting integer to string C++?

最满意答案

现在在c ++ 11我们有

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

链接到参考: http : //en.cppreference.com/w/cpp/string/basic_string/to_string

Now in c++11 we have

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

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

更多推荐

本文发布于:2023-08-06 11:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1447652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:integer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!