c++ - 添加到文件名前面

标签 c++ arrays pointers

我正在尝试在动态创建的文件名前面添加一些内容:

fstream a;
string f = argv[1];
string  fw = f.substr(0, f.rfind("."));
const char* pre = 'my_';
a.open(pre + fw.c_str(), fstream::out | fstream::in | fstream::trunc);
a.close();
a.open(pre + fw.c_str(), fstream::out | fstream::in | fstream::trunc);

但显然我不能使用 + 运算符来加入这个。 错误:

invalid operands of types ‘const char*’ and ‘const char*’ to binary ‘operator +

也适用于我得到的 my_ 语句

invalid conversion from ‘int’ to ‘const char*’

最佳答案

尝试以下操作。

const std::string pre="my_";
a.open((pre + fw).c_str(), fstream::out | fstream::in | fstream::trunc);

根据您的编译器及其版本,您甚至可以使用以下代码(不需要 .c_str() 部分)。

a.open(pre + fw, fstream::out | fstream::in | fstream::trunc);

关于c++ - 添加到文件名前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32925099/

相关文章:

c++ - C++中的cin缓冲区问题

c++ - 向函数添加具有默认值的参数是否会破坏 ABI?

c++ - 将函数作为参数传递给方法 C++

c - 从字节的 char[] 中获取 int

c++ - 为什么要写 -> 而不是 .?

c++ - PC 上的 C++ 和 Arduino 之间的 Sizeof() 区别

Java 优化字符串与字符数组

c++ - 从函数 C++ 返回数组

c++ - 对象的动态数组与指针的动态数组

c - 使用 uint8_t 为双数组分配内存