C++ std::stringstream 和 std::ios::binary
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2311382/
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
std::stringstream and std::ios::binary
提问by rioki
I want to write to a std::stringstream
without any transformation of, say line endings.
我想写一个std::stringstream
没有任何转换的,比如行尾。
I have the following code:
我有以下代码:
void decrypt(std::istream& input, std::ostream& output)
{
while (input.good())
{
char c = input.get()
c ^= mask;
output.put(c);
if (output.bad())
{
throw std::runtime_error("Output to stream failed.");
}
}
}
The following code works like a charm:
下面的代码就像一个魅力:
std::ifstream input("foo.enc", std::ios::binary);
std::ofstream output("foo.txt", std::ios::binary);
decrypt(input, output);
If I use a the following code, I run into the std::runtime_error
where output is in error state.
如果我使用以下代码,我会遇到std::runtime_error
输出处于错误状态的地方。
std::ifstream input("foo.enc", std::ios::binary);
std::stringstream output(std::ios::binary);
decrypt(input, output);
If I remove the std::ios::binary
the decrypt function completes without error, but I end up with CR,CR,LF as line endings.
如果我删除std::ios::binary
解密功能完成没有错误,但我最终以 CR,CR,LF 作为行结尾。
I am using VS2008 and have not yet tested the code on gcc. Is this the way it supposed to behave or is MS's implementation of std::stringstream
broken?
我使用的是 VS2008,还没有在 gcc 上测试代码。这是它应该表现的方式还是MS的实现方式已std::stringstream
损坏?
Any ideas how I can get the contents into a std::stringstream
in the proper format? I tried putting the contents into a std::string
and then using write()
and it also had the same result.
任何想法如何std::stringstream
以正确的格式将内容转换为 a ?我尝试将内容放入 astd::string
然后使用write()
它也有相同的结果。
回答by éric Malenfant
AFAIK, the binary
flag only applies to fstream
, and stringstream
never does linefeed conversion, so it is at most useless here.
AFAIK,该binary
标志仅适用于fstream
,stringstream
从不进行换行转换,因此在这里它最多没用。
Moreover, the flags passed to stringstream
's ctor should contain in
, out
or both. In your case, out
is necessary (or better yet, use an ostringstream
) otherwise, the stream is in not in output mode, which is why writing to it fails.
此外,传递给stringstream
ctor的标志应该包含in
,out
或者两者都包含。在您的情况下,out
是必要的(或者更好的是,使用ostringstream
),否则,流不处于输出模式,这就是写入它失败的原因。
stringstream
ctor's "mode" parameter has a default value of in|out
, which explains why things are working properly when you don't pass any argument.
stringstream
ctor 的“mode”参数的默认值为in|out
,这解释了为什么当您不传递任何参数时事情正常工作。
回答by Miollnyr
Try to use
尝试使用
std::stringstream output(std::stringstream::out|std::stringstream::binary);