该代码应该与.txt和_r.txt连接argv [1].
std::stringstream sstm;
std::stringstream sstm_r;
sstm<<argv[1]<<".txt";
sstm_r<<argv[1]<<"_r.txt";
const char* result = sstm.str().c_str();
const char* result_r = sstm_r.str().c_str();
fs.open(result);
fs_r.open(result_r);
cout<<result<<endl;
cout<<result_r<<endl;
Run Code Online (Sandbox Code Playgroud)
但它的作用是,当我输入"abc"作为argv [1]时,它给了我,结果为"abc_r.tx0",result_r也是"abc_r.tx0".这是怎样的正确方法,为什么是这个错了.
std::string返回的指针c_str()所关联的实例将被销毁,result并将其result_r作为悬空指针销毁,从而导致未定义的行为.std::string如果要使用,则需要保存实例c_str():
const std::string result(sstm.str());
fs.open(result.c_str()); /* If this is an fstream from C++11 you
can pass a 'std::string' instead of a
'const char*'. */
Run Code Online (Sandbox Code Playgroud)