std :: stringstream和std :: ios :: binary [英] std::stringstream and std::ios::binary

查看:767
本文介绍了std :: stringstream和std :: ios :: binary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个 std :: stringstream 而不进行任何转换,说行尾。

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

我有以下代码:

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.");
        }
    }
}

charm:

std::ifstream input("foo.enc", std::ios::binary);
std::ofstream output("foo.txt", std::ios::binary);
decrypt(input, output);

如果我使用下面的代码,我会遇到 std ::

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);

如果我删除 std :: ios :: binary 解密函数完成没有错误,但我最终以CR,CR,LF作为行结束。

If I remove the std::ios::binary the decrypt function completes without error, but I end up with CR,CR,LF as line endings.

我使用VS2008,还没有测试代码在gcc。这是它应该的行为或MS的实现 std :: stringstream 坏了吗?

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?

任何想法我可以得到的内容到一个 std :: stringstream 在正确的格式?我尝试将内容放入 std :: string ,然后使用 write(),它也有相同的结果。

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.

推荐答案

AFAIK, binary 标志仅适用于 fstream stringstream 从不进行换行,因此这里最无用。

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

此外,传递给 stringstream 的ctor的标志应包含 in out 或两者。在你的case, out 是必要的(或更好的是,使用 ostringstream )否则,流不在输出模式,这就是写入失败的原因。

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的mode参数的默认值为 in | out ,这说明为什么当您不传递任何参数时,操作正常。

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.

这篇关于std :: stringstream和std :: ios :: binary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆