将整数转换为字符串C ++ [英] converting integer to string C++

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

问题描述

  int i = 5;我想要将整数转换为char数组, 
std :: string s;
std :: stringstream out;
out<<一世;
s = out.str();

但是当我尝试打印 s 它仍然打印5.我不知道它应该这样做还是我做错了什么?除此之外,我更喜欢如果我可以转换相同的int到char数组。但我会感谢任何帮助在这件事。
谢谢!
代码摘自:替代itoa()将整数转换为字符串C ++?

解决方案





  char * charPtr = new char [s.length )+ 1]; // s是代码片段中的字符串
strcpy(charPtr,s.c_str());

// .......

delete [] charPtr; //应该这样做,否则内存泄漏。


I am trying to convert an integer to char array and I came across this piece of code

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

But when I try to print the value of s it still prints 5. I don't know if its supposed to do that or am I doing something wrong? Besides I would prefer if I could convert the same int to char array. But I would appreciate any help in the matter. Thanks! Code taken from: Alternative to itoa() for converting integer to string C++?

解决方案

Besides I would prefer if I could convert the same int to char array.

char *charPtr = new char[ s.length() + 1 ] ; // s is the string in the snippet posted
strcpy( charPtr, s.c_str() ) ;

// .......

delete[] charPtr ; // Should do this, else memory leak.

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

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