rio*_*oki 6 c++ iostream visual-studio-2008
我想写一个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.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下代码就像一个魅力:
std::ifstream input("foo.enc", std::ios::binary);
std::ofstream output("foo.txt", std::ios::binary);
decrypt(input, output);
Run Code Online (Sandbox Code Playgroud)
如果我使用以下代码,我会遇到std::runtime_error输出处于错误状态的位置.
std::ifstream input("foo.enc", std::ios::binary);
std::stringstream output(std::ios::binary);
decrypt(input, output);
Run Code Online (Sandbox Code Playgroud)
如果我删除了std::ios::binary解密函数完成没有错误,但我最终得到CR,CR,LF作为行结尾.
我正在使用VS2008并且尚未在gcc上测试代码.这是它应该表现的方式还是MS的std::stringstream破坏实现?
有什么想法我怎么能std::stringstream以适当的格式把内容?我尝试将内容放入a std::string然后使用write(),它也有相同的结果.
Éri*_*ant 12
AFAIK,该binary标志仅适用于fstream,并且stringstream从不进行换行转换,因此它在这里至多无用.
此外,传递给标志stringstream的构造函数应该包含in,out或两者兼而有之.在你的情况下,out是必要的(或者更好的是,使用一个ostringstream)否则,流不处于输出模式,这就是写入它失败的原因.
stringstreamctor的"mode"参数有一个默认值in|out,它解释了当你没有传递任何参数时事情正常工作的原因.