把字符串和字符放在ofstream中

时间:2013-12-13 14:23:31

标签: c++ file makefile

我想将字符串和字符放在ofstream()中但是我得到错误我想用不同的名称创建文件,但是在相同的路径中,例如像E://string.txt但是字符串是可变的 你能救我吗?

#include <iostream>
#include <ofstream>
using namespace std;
int main()
{
  string filename;
  ofstream note("E://"filename".txt",ios::app);
}

你能明白我的观点吗? 我知道我的代码错了,但帮我解决了!

1 个答案:

答案 0 :(得分:1)

您可以使用stringstream形成路径,然后在需要时从该流中提取C字符串以构建ofstream

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);
}