converting integer to string C++

浪子不回头ぞ 提交于 2019-12-06 16:38:33

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.

Yes, it's supposed to do that. You'd (primarily) notice the difference from just printing a number out directly if you do some other string-type manipulation on the result (e.g., concatenating it with other strings, searching for characters in the string).

Just for example:

std::cout << i+i;   // should print "10"
std::cout << s+s;   // should print "55"

If you would like to stop worrying about issues like that you might be interested in boost/lexical_cast.hpp.

#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>

int main() {
  const int i=5;
  const char* s = boost::lexical_cast<std::string>(i).c_str();
  std::cout << s << std::endl;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!