将ostream的内容复制到另一个ostream

问题描述 投票:1回答:1

我正在寻找一种方法将内容从一个ostream复制到另一个。我有以下代码:

std::ostringsteam oss;

oss << "stack overflow";

{
    //do some stuff that may fail
    //if it fails, we don't want to create the file below!
}

std::ofstream ofstream("C:\\test.txt");

//copy contents of oss to ofstream somehow

任何帮助表示赞赏!

c++ c++11 ostream
1个回答
5
投票

有什么不妥

ofstream << oss.str();

?

如果你想使用ostream基类,那么这是不可能的,因为就ostream而言,所写的任何内容都将永远消失。您必须使用以下内容:

// some function
...
  std::stringstream ss;

  ss << "stack overflow";
  ss.seekg(0, ss.beg);

  foo(ss);
...

// some other function
void foo(std::istream& is)
{
  std::ofstream ofstream("C:\\test.txt");
  ofstream << is.rdbuf();
}
© www.soinside.com 2019 - 2024. All rights reserved.