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.
A stringstream object, whose value is moved. Open mode: Access given by the internal stringbuf object to its internal sequence of characters. It is an object of member type openmode for which any combination of the following member values is significant:
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.
The class template std::basic_stringstream implements input and output operations on string based streams. It effectively stores an instance of std::basic_string and performs the input and output operations on it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With