test11 test11 - 1 year ago 151
C++ Question

converting string stream to char*

I have the following code

const char * getFileName(std::string filePath, std::string theDestDirectory)
size_t lastOfParentDirectory = filePath.find_last_of("\\");
size_t extentionPos = filePath.substr(lastOfParentDirectory + 1).find_last_of(".");
std::stringstream convertedFilePath;
convertedFilePath << theDestDirectory << "\\" << filePath.substr(lastOfParentDirectory + 1).substr(0, extentionPos) << ".stl";
return convertedFilePath.str().c_str();

what I am trying to do is to get new file path and change the extention of the file. I need the output to be of type const char * since the other processing sould be in char *

the upper code compiles but give a nonsence outputoutput

Answer Source

The convertedFilePath variable is local inside the getFileName function. Once the function returns the stream is destructed, and the string it holds is destructed with it. That means the pointer you return now points to a destructed string, and dereferencing it will lead to undefined behavior.

The simple solution is of course to return a std::string instead. If you need a const char* later, you can always use the c_str function on the returned object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download