将字符串和字符放入流中

put string and character in ofstream

本文关键字:字符 字符串      更新时间:2023-10-16

我想在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);
}