将 stringstream 内容写入 ofstream

发布于 2024-07-09 16:21:01 字数 623 浏览 6 评论 0原文

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

std::ofstream outFile;
outFile.open(output_file);

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

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

现在我的 outFile 只包含垃圾:“0012E708”到处重复。

GetHolesResults 中,我可以编写

outFile << "Foo" << std:endl; 

,它将在 outFile 中正确输出。

对我做错了什么有什么建议吗?

I'm currently using std::ofstream as follows:

std::ofstream outFile;
outFile.open(output_file);

Then I attempt to pass a std::stringstream object to outFile as follows:

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

Now my outFile contains nothing but garbage: "0012E708" repeated all over.

In GetHolesResults I can write

outFile << "Foo" << std:endl; 

and it will output correctly in outFile.

Any suggestion on what I'm doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

喵星人汪星人 2024-07-16 16:21:01

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

outFile << ss.rdbuf();

You can do this, which doesn't need to create the string. It makes the output stream read out the contents of the stream on the right side (usable with any streams).

outFile << ss.rdbuf();
轻拂→两袖风尘 2024-07-16 16:21:01

如果您使用 std::ostringstream 并想知道为什么 ss.rdbuf() 没有写入任何内容,那么请使用 .str() 函数。

outFile << oStream.str();

If you are using std::ostringstream and wondering why nothing get written with ss.rdbuf() then use .str() function.

outFile << oStream.str();
慕烟庭风 2024-07-16 16:21:01

将 stringstream rdbuf 传递到流时,换行符不会被翻译。 输入文本可以包含 \n 因此查找替换不起作用。 旧代码写入 fstream 并将其切换到 stringstream 会丢失 endl 翻译。

When passing a stringstream rdbuf to a stream newlines are not translated. The input text can contain \n so find replace won't work. The old code wrote to an fstream and switching it to a stringstream losses the endl translation.

梦回梦里 2024-07-16 16:21:01

我宁愿写 ss.str(); 而不是 ss.rdbuf(); (并使用字符串流)。

如果您使用 ss.rdbuf() ,则 outFile 的格式标志将被重置,从而使您的代码不可重用。
即,GetHolesResults(..., std::ofstream &outFile) 的调用者可能想要编写类似这样的内容以在表中显示结果:

outFile << std::setw(12) << GetHolesResults ...

...并想知道为什么宽度是被忽略。

I'd rather write ss.str(); instead of ss.rdbuf(); (and use a stringstream).

If you use ss.rdbuf() the format-flags of outFile will be reset rendering your code non-reusable.
I.e., the caller of GetHolesResults(..., std::ofstream &outFile) might want to write something like this to display the result in a table:

outFile << std::setw(12) << GetHolesResults ...

...and wonder why the width is ignored.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文