将字符串和字符放入流中
put string and character in ofstream
我想在ofstream()
中把字符串和字符放在一起,但我遇到了错误。我想用不同的名称但在相同的路径中创建文件,例如像这个E://string.txt
,但字符串是可变的你能帮我吗?
#include <iostream>
#include <ofstream>
using namespace std;
int main()
{
string filename;
ofstream note("E://"filename".txt",ios::app);
}
你能明白我的意思吗?我知道我的代码是错误的,但帮我修复它!
您可以使用stringstream
形成路径,然后在构建ofstream
:时从该流中提取C字符串
std::stringstream path;
path << "E:/" << foo() << ".txt";
std::ofstream ofs(path.str().c_str());
如果你只需要连接字符串和字符,你可能可以在没有流的情况下(我们在上面使用了它的格式化功能):
const std::string path = "E:/" + foo() + ".txt";
std::ofstream ofs(path.c_str());
在C++03中,由于历史原因,ofstream
构造函数需要一个C字符串(.c_str()
),尽管这在C++11:中是固定的
const std::string path = "E:/" + foo() + ".txt";
std::ofstream ofs(path);
使用您的新示例:
#include <iostream>
#include <fstream>
int main()
{
string filename;
ofstream note(("E:/" + filename + ".txt").c_str(), ios::app);
}
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数