将串流内容写入流中

Eri*_*ric 47 c++ parameters stl stringstream ofstream

我目前正在使用std::ofstream如下:

std::ofstream outFile;
outFile.open(output_file);
Run Code Online (Sandbox Code Playgroud)

然后我尝试将std::stringstream对象传递给outFile如下:

GetHolesResults(..., std::ofstream &outFile){
  float x = 1234;
  std::stringstream ss;
  ss << x << std::endl;
  outFile << ss;
}
Run Code Online (Sandbox Code Playgroud)

现在我只outFile包含垃圾:"0012E708"重复了一遍.

GetHolesResults我可以写

outFile << "Foo" << std:endl; 
Run Code Online (Sandbox Code Playgroud)

并且它将正确输出outFile.

关于我做错了什么的任何建议?

Joh*_*itb 81

您可以这样做,不需要创建字符串.它使输出流在右侧读出流的内容(可用于任何流).

outFile << ss.rdbuf();
Run Code Online (Sandbox Code Playgroud)

  • 我很好奇:为什么这个解决方案适用于`std :: stringstream`而不适用于`std :: ostringstream`?在第二种情况下,我得到一个空文件. (10认同)
  • @JaviV因为你可以[只写](http://en.cppreference.com/w/cpp/io/basic_ostream)到`std :: oANYSTREAM`并且只能读取`std :: iANYSTREAM`.如果`output_stream`也有`read`操作,那就没有意义了.如果你需要两个只使用`std :: ANYSTREAM`而你就在家:) (8认同)

Dig*_*ity 15

如果你正在使用std::ostringstream并想知道为什么没有写入ss.rdbuf()然后使用.str()函数.

outFile << oStream.str();
Run Code Online (Sandbox Code Playgroud)

  • 你的回答让我得到了以下认识:从`s`获得`char`数组,你可以做`ss.str().c_str()`.(只是为了新手的利益而张贴在这里,以便将来偶然发现.) (8认同)
  • @Digital_Reality,谢谢!当我使用 rdbuff 时,没有任何内容被写入。这是什么原因呢? (2认同)