代码之家  ›  专栏  ›  技术社区  ›  rioki

std::stringstream和std::ios::binary

  •  6
  • rioki  · 技术社区  · 16 年前

    我想写信给 std::stringstream 没有任何转换,比如行尾。

    我有以下代码:

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

    以下代码的工作方式很有魅力:

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

    如果我使用以下代码,我会遇到 std::runtime_error 其中输出处于错误状态。

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

    如果我移除 std::ios::binary decrypt函数完成时没有出错,但是我以cr、cr、lf作为行尾。

    我使用的是VS2008,还没有在GCC上测试代码。这是它应该表现的方式还是MS的实现 标准::字符串流 破了?

    我能把里面的东西 标准::字符串流 以正确的格式?我试着把里面的东西放到 std::string 然后使用 write() 结果也一样。

    2 回复  |  直到 16 年前
        1
  •  12
  •   Éric Malenfant    16 年前

    阿飞 binary 标志仅适用于 fstream 和 stringstream 从不进行换行,所以在这里最多是没用的。

    此外,传递给 横流 的ctor应包含 in , out 或者两者兼而有之。在你的情况下, 外面的 是必要的(或者更好的是,使用 ostringstream )否则,流不处于输出模式,这就是写入它失败的原因。

    横流 ctor的“模式”参数的默认值为 in|out 这就解释了为什么当你没有通过任何争论的时候事情会正常工作。

        2
  •  -2
  •   Miollnyr    16 年前

    尝试使用

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