在 C++ 中将 int 转换为字符串的最简单方法 [英] Easiest way to convert int to string in C++

查看:108
本文介绍了在 C++ 中将 int 转换为字符串的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中将 int 转换为等效的 string 的最简单方法是什么?我知道两种方法.有没有更简单的方法?

What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?

(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

推荐答案

C++11 引入 std::stoi(以及每个数字类型的变体)和 std::to_string,C atoiitoa 的对应物,但用术语表示std::string.

C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.

#include <string> 

std::string s = std::to_string(42);

因此是我能想到的最短方法.您甚至可以省略命名类型,使用 auto 关键字:

is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:

auto s = std::to_string(42);

注意:参见[string.conversions](n3242)

Note: see [string.conversions] (21.5 in n3242)

这篇关于在 C++ 中将 int 转换为字符串的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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