C++ 字符串流连接查询

标签 c++ string

代码应该将 argv[1] 与 .txt 和 _r.txt 连接起来。

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;

但它的作用是, 当我输入“abc”作为 argv[1] 时,它给我结果为“abc_r.tx0”,result_r 也相同“abc_r.tx0”。正确的方法是什么,为什么这是错误的。

最佳答案

c_str() 返回的指针关联的 std::string 实例将被销毁,留下 result result_r 作为悬空指针,导致未定义的行为。如果要使用 c_str(),则需要保存 std::string 实例:

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*'. */

关于C++ 字符串流连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12388882/

相关文章:

iphone - Obj-C 组合字符串

python - 在 Python 中使用字典替换子字符串

c++ - 虚拟处理器和高级网络 linux 和 windows

c++ - Bazel,带有 mingw64 编译器的 Windows 10 工具链配置

c++ - 如何使用 STL 排序函数根据第二列对二维数组进行排序?

使用\r\n 时的 Python 额外行写入(在 VS 代码中)

python - 如何转义通过用户输入收到的 latex 代码?

c++ - memset, memcpy with new 运算符

C++读取字节问题

java - 使用字符索引 HashMap 时出现 NullPointerException