This is a portion of my simple program
string appData = getenv("APPDATA");
const char *mypath= (appData+"\\MyApplication\\hello.txt").c_str();
cout << mypath;
// output: c:\users\xrobot\appdata\Roaming\Myapplication\hello.txt
fstream file(mypath,ios::in);
ofstream filetemp;
filetemp.open("world.bak");
cout << mypath;
// output: É↕7
Why is mypath changed in that weird string ?
You should use
std::stringas:then do this:
Note that you must not do this:
It is because expression on the right hand side is a temporary which gets destroyed at the end of the expression and
mypathwill continue to point to the destroyed object. It becomes a dangling pointer, in other words.—
Because in your posted code,
mypathis a dangling pointer, using which invokes undefined behavior.This is how you should write the code: