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

久未见 提交于 2019-12-12 10:47:45

问题


I want to write to a std::stringstream without any transformation of, say line endings.

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::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.

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?

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.


回答1:


AFAIK, the binary flag only applies to fstream, and stringstream never does linefeed conversion, so it is at most useless here.

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's "mode" parameter has a default value of in|out, which explains why things are working properly when you don't pass any argument.




回答2:


Try to use

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


来源:https://stackoverflow.com/questions/2311382/stdstringstream-and-stdiosbinary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!