开发者

converting integer to string C++

开发者 https://www.devze.com 2023-02-22 19:44 出处:网络
I am trying to convert an integer to char array and I came across this piece of code int i = 5; std::string s;

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 pr开发者_运维技巧ints 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++?


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"


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消