且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将整数转换为字符串C ++

更新时间:2022-10-17 21:22:09





  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.