C++ 将字符串流内容写入 ofstream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/324711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing stringstream contents into ofstream
提问by Eric
I'm currently using std::ofstream
as follows:
我目前使用std::ofstream
如下:
std::ofstream outFile;
outFile.open(output_file);
Then I attempt to pass a std::stringstream
object to outFile
as follows:
然后我尝试将一个std::stringstream
对象传递给outFile
如下:
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.
现在我只outFile
包含垃圾:“0012E708”到处重复。
In GetHolesResults
I can write
在GetHolesResults
我可以写
outFile << "Foo" << std:endl;
and it will output correctly in outFile
.
它将在outFile
.
Any suggestion on what I'm doing wrong?
关于我做错了什么的任何建议?
回答by Johannes Schaub - litb
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();
回答by Digital_Reality
If you are using std::ostringstream
and wondering why nothing get written with ss.rdbuf()
then use .str()
function.
如果您正在使用std::ostringstream
并想知道为什么没有写入内容,请ss.rdbuf()
使用.str()
函数。
outFile << oStream.str();
回答by 2ndshot
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.
将 stringstream rdbuf 传递给流时,不会转换换行符。输入文本可以包含\n
因此查找替换将不起作用。旧代码写入 fstream 并将其切换到 stringstream 会丢失 endl 转换。
回答by chipsbarrier
I'd rather write ss.str();
instead of ss.rdbuf();
(and use a stringstream).
我宁愿写ss.str();
而不是ss.rdbuf();
(并使用字符串流)。
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:
如果您使用ss.rdbuf()
format-flagsoutFile
将被重置呈现您的代码不可重用。即,调用者GetHolesResults(..., std::ofstream &outFile)
可能想写这样的东西来在表格中显示结果:
outFile << std::setw(12) << GetHolesResults ...
...and wonder why the width is ignored.
...并想知道为什么忽略宽度。