temp_str.str()
is a temporary string
value, destroyed at the end of the statement. cstr2
is then a dangling pointer, invalidated when the array it pointed to was deleted by the string's destruction.
You'll need a non-temporary string if you want to keep hold of a pointer to it:
string str = temp_str().str(); // lives as long as the current block
const char* cstr2 = str.c_str(); // valid as long as "str" lives
Modern C++ also has slightly more convenient string conversion functions:
string str = std::to_string(fileNameIndex);
const char* cstr2 = str.c_str(); // if you really want a C-style pointer
Again, this returns a string
by value, so don't try cstr2 = to_string(...).c_str()