test11 test11 - 25 days ago 11
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

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.