Getting char* array from c++ stringstream ostringstream -
i trying copy ostringstream char* array , hoping can me understanding mistake lies. looked on forum, found things similar , unfortunately still unable property copy ostringstream char*. in short trying copy char* via:
ostringstream bld bld<<"test"<<"is"<<"good" const char * result = bld.str().c_str();
the complete code reproduce error below. in code having 2 functions build strings via ostringstream. in makefilepath() function build complete file path (ie /path/file.txt). in add() function, add 2 more char* arrays argument prefix /path/file.txt suffix.
the problem unknown reason me fullfilepath changes prefix /path/file.txt suffix. last 3 lines of code exhibit that.
i spent hours on this, thinking maybe referencing issue or else. however, none attemped worked. ideas how on problem?
thanks!!
#include <iostream> #include <sstream> #include <string> using std::cout; using std::endl; using std::string; using std::ostringstream; const char* add(const char *filename) { ostringstream bld; const char *prefix = "prefix"; const char *suffix = "suffix"; bld << prefix << " " << filename << " " << suffix; string temp = bld.str(); cout << "in add(): \n\t" << temp << endl; return temp.c_str(); } const char * makefilepath(const char *path, const char *name, const char *ext = ".txt") { ostringstream bld; bld << path << name << ext; cout << "makefilepath(), returning: \n\t" << bld.str()<< endl; string temp = bld.str(); return temp.c_str(); } int main(int argc, char **argv) { cout << "=== project start ===" << endl; const char * filepath = "\\path\\"; const char *filename = "filename"; const char *fullfilepath = makefilepath(filepath, filename); cout << fullfilepath before calling add():\n\t" << fullfilepath << endl; const char* str = add(fullfilepath); cout << fullfilepath after calling add():\n\t" << fullfilepath << endl; return 1; }
the short answer need use strdup
fix this:
const char* makefilepath(const char *path, const char *name, const char *ext = ".txt") { ostringstream bld; bld << path << name << ext; cout << "makefilepath(), returning: \n\t" << bld.str()<< endl; return strdup(bld.str().c_str()); }
this sub-optimal solution have memory leak unless free
result of function, plus might return null
on occasion cause chaos if don't test it. it'd better return std::string
.
if you're using c++, use c++.
Comments
Post a Comment