elliott.david 2011-04-08 04:19 采纳率: 25%
浏览 800
已采纳

在 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();

转载于:https://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c

  • 写回答

24条回答 默认 最新

  • 喵-见缝插针 2011-04-08 06:13
    关注

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

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(23条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题