tags:

views:

452

answers:

2

Or ostringstream?

istringstream a("asd");
istringstream b = a; // This does not work.

I guess memcpy won't work either.

+2  A: 

You can't just copy streams, you have to copy their buffers using iterators. For example:

#include <sstream>
#include <algorithm>
......
std::stringstream first, second;
.....
std::istreambuf_iterator<char> begf(first), endf;
std::ostreambuf_iterator<char> begs(second);
std::copy(begf, endf, begs);
AraK
Isn't copying one character at a time slow?
Łukasz Lew
Have you measured it?
AraK
I measured it when input was a file ifstringstream. The difference was tremendous.
Łukasz Lew
There is nothing called ifstringstream in C++. Could you post the code you wrote?
AraK
Why would you copy the contents of fstream into stringstream?
AraK
+5  A: 
istringstream a("asd");
istringstream b(a.str());

Edit: Based on your comment to the other reply, it sounds like you may also want to copy the entire contents of an fstream into a strinstream. You don't want/have to do that one character at a time either (and you're right -- that usually is pretty slow).

// create fstream to read from
std::ifstream input("whatever");

// create stringstream to read the data into
std::istringstream buffer;

// read the whole fstream into the stringstream:
buffer << input.rdbuf();
Jerry Coffin
+1 I didn't know there is an overloading for buffers!
AraK
Yeah, it's one of those cute little tricks that almost nobody knows about. Not useful all that often, but when you want what it does, it makes things quite a bit simpler.
Jerry Coffin
Shouldn't that be `ostringstream` instead of `istringstream`?
Allen George