ostringstream
Is there a way to make a char* (or char string) equal to a ostringstream.str()? In the tutorial below, a "string" is equal to an ostringstream.str(). That''ll obviously compile, but I tried making a "char *mystr = oss.str()" and I get errors with that. I swear I''ve seen this done with a char string on this forum...or one of the many other forums here! But I forgot to bookmark it or something--I never found it again Thanks in advance.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
ostringstream oss;
string mystr;
oss << "Sample string";
mystr=oss.str(); // <---- RIGHT HERE
cout << mystr;
return 0;
}
well , I do not know whether u can type caste , but if a
char* is all that u want then u can very well do that
char * mystr
mystr = oss.str().c_str() ;
This should work fine...
char* is all that u want then u can very well do that
char * mystr
mystr = oss.str().c_str() ;
This should work fine...
No, that won''t because std::string::c_str() returns a const char *, and if you make mystr a const char *, it will point to deallocated memory once the ostringstream goes out of scope. If you have some grudge against using std::string, then you should do:
char mystr[256];
strcpy(mystr, oss.str().c_str());
char mystr[256];
strcpy(mystr, oss.str().c_str());
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement