modifying streambuf of an istream object

Hello.
I want to strip away "comments" from my istream and rewind it. (this might be a bad idea, let me know)
My "comments" start with std::string delimiter and end at the end of the line.
delimiter might be whatever, so it may contain (at the beginning middle, or end) some blanks (so using as a delimiter " This might be the delimiter ") must work.
(add as many blanks as you like in any position)
I did something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void IgnoreCommentsAndRewind(std::istream * source, std::string const & delimiter)
{
	stringstream * destination = new stringstream();
	//some code that fills destination only with what I need: so far so good

	//I want to swap the buffers of the destination and source.
	//Or I want to set the underlying streambuf obj of source to contain what is in destination

	streambuf * good = destination->rdbuf(), *bad=source->rdbuf();
		
	source->rdbuf(good);//<-it works, but what happens to the "bad"?
	destination->rdbuf(bad);//<-this doesn't even compile because stringstream has only the function rdbuf(void) const
	source->seekg(0,ios_base::beg);//"rewind"
	delete destination; //delete the ostream. This cause the "good" streambuf to be destroyed
}

I tried also ostream * ptr = destination (valid since sstream is a ofstream), and then the same sintax, but I run through a run time error (which I can't understand)

I tried also to use pubsetbuf (in many different ways, here is an example)
1
2
3
4
5
6
7
8
9
10
11
streambuf * myAnsw;
		
		char * ptrToBuf = new char[destination->str().size()+1];
		
		for (unsigned int i = 0; i <= destination->str().size();i++)
 			ptrToBuf[i]=destination->str()[i];

		source->rdbuf()->pubsetbuf (0,0);
		myAnsw = source->rdbuf()->pubsetbuf (ptrToBuf,destination->str().size()+1);
		source->seekg(0,ios_base::beg);
		delete destination;			//delete the ostream 

But it is not actually using the ptrToBuf as buffer: the std::istream * source still contains all the comments.
Thank you for the help.
It sounds like you're (at the beginning of) reimplementing the boost.iostreams library. Perhaps you could simply use the library itself? Take a look at the "Writing Filters" section of the boost.iostreams library tutorial: http://www.boost.org/doc/libs/release/libs/iostreams/doc/tutorial/tutorial.html


I was trying to stay stick to standard library. I will definitly give it a look.
Topic archived. No new replies allowed.