将 stringstream 内容写入 ofstream
我目前正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以这样做,不需要创建字符串。 它使输出流读出右侧流的内容(可与任何流一起使用)。
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).
如果您使用
std::ostringstream
并想知道为什么ss.rdbuf()
没有写入任何内容,那么请使用.str()
函数。If you are using
std::ostringstream
and wondering why nothing get written withss.rdbuf()
then use.str()
function.将 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.我宁愿写
ss.str();
而不是ss.rdbuf();
(并使用字符串流)。如果您使用 ss.rdbuf() ,则 outFile 的格式标志将被重置,从而使您的代码不可重用。
即,
GetHolesResults(..., std::ofstream &outFile)
的调用者可能想要编写类似这样的内容以在表中显示结果:...并想知道为什么宽度是被忽略。
I'd rather write
ss.str();
instead ofss.rdbuf();
(and use a stringstream).If you use
ss.rdbuf()
the format-flags ofoutFile
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:...and wonder why the width is ignored.