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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:59:24  来源:igfitidea点击:

std::stringstream and std::ios::binary

c++visual-studio-2008iostream

提问by rioki

I want to write to a std::stringstreamwithout 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_errorwhere 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::binarythe 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::stringstreambroken?

我使用的是 VS2008,还没有在 gcc 上测试代码。这是它应该表现的方式还是MS的实现方式已std::stringstream损坏?

Any ideas how I can get the contents into a std::stringstreamin the proper format? I tried putting the contents into a std::stringand then using write()and it also had the same result.

任何想法如何std::stringstream以正确的格式将内容转换为 a ?我尝试将内容放入 astd::string然后使用write()它也有相同的结果。

回答by éric Malenfant

AFAIK, the binaryflag only applies to fstream, and stringstreamnever does linefeed conversion, so it is at most useless here.

AFAIK,该binary标志仅适用于fstreamstringstream从不进行换行转换,因此在这里它最多没用。

Moreover, the flags passed to stringstream's ctor should contain in, outor both. In your case, outis necessary (or better yet, use an ostringstream) otherwise, the stream is in not in output mode, which is why writing to it fails.

此外,传递给stringstreamctor的标志应该包含inout或者两者都包含。在您的情况下,out是必要的(或者更好的是,使用ostringstream),否则,流不处于输出模式,这就是写入它失败的原因。

stringstreamctor's "mode" parameter has a default value of in|out, which explains why things are working properly when you don't pass any argument.

stringstreamctor 的“mode”参数的默认值为in|out,这解释了为什么当您不传递任何参数时事情正常工作。

回答by Miollnyr

Try to use

尝试使用

std::stringstream output(std::stringstream::out|std::stringstream::binary);