"JustSomeGuy" <No***@ucalgary.ca> wrote in message
news:41***************@ucalgary.ca...
Ali Çehreli wrote:
"JustSomeGuy" <No***@ucalgary.ca> wrote in message
news:41***************@ucalgary.ca... I am passing an istringstream to a function. I want that function to
get a copy of the istringstream and not a refrence to it.
istringstream (and possibly any stream) cannot be copied.
ie when the function returns I want the istringstream to be
unmodified...
However when I try to pass it
fn(istringstream s) // doesn't compile
but
fn(istringstream & s) // does.
How about passing it by const reference:
void fn(istringstream const & s);
But then, you can't do much with a const input stream anyway. What are
trying to achieve?
Just tying to extract data from the stream and leave it the same state.
Unfortunately this is not guaranteed to work for input streams. Think about
the standard input: Characters taken out of it are gone forever unless we
save them.
The best you can do is to save all of the characters into a stream. Then you
can use seekg to set the read position before returning from your function.
The following program worked for me. Send two words to the standard input of
the program to see that consecutive calls to foo maintain the read position
of the stream.
#include <sstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
class PositionSaver
{
istream & is_;
ios::pos_type position_;
public:
explicit PositionSaver(istream & is)
:
is_(is),
position_(is_.tellg())
{}
~PositionSaver()
{
is_.seekg(position_);
}
};
void foo(istream & input)
{
PositionSaver const position_saver(input);
string first_word;
input >> first_word;
cout << "first word read in foo : " << first_word << '\n';
}
int main()
{
stringstream my_stream;
copy(istream_iterator<string>(cin),
istream_iterator<string>(),
ostream_iterator<string>(my_stream, " "));
string first_word;
my_stream >> first_word;
cout << "first word read in main: "
<< first_word << '\n';
foo(my_stream);
foo(my_stream);
}
Ali