Relatively simple iostream question

Started by
4 comments, last by Sharlin 19 years, 1 month ago
It appears that while the tutorial I'm primarily using indicates that iostream's << [and put/write I'd wager] insert stuff into the stream, it appears to overwrite things into the stream:

> ./testss2
moocow
mooxxx
> more testss2.cc
#include <iostream>
#include <string>
#include <sstream>

using namespace std;
int main(){
string  moo="moocow";
string  xxx="xxx";
stringstream ss;
streampos       x=3;

ss << moo;
cout << ss.str() << "\n";
ss.seekp(ss.tellp()-x);
ss << xxx;
cout << ss.str() << "\n";
}

Is there any pre-made STL friendly way to insert rather than overwrite?
Advertisement
Break moocow into two strings; moo1 and moo2. Then, ss << moo1 << xxx << moo2;
<< inserts at the current positions in the stream, so if the stream pos is at the beginning it is overwrite, if its at the end, its adding (in general) ... obviously they're are various forms or streams, stringstreams, etc ...
Here's the best I could come up with:

#include <iostream>#include <string>#include <sstream>using namespace std;int main(){	string  moo="moocow";	string  xxx="xxx";	stringstream ss;	streampos       x=3;	ss.sync();	ss << moo;	cout << ss.str() << "\n";	string s = ss.str();	s.insert( ss.tellp() - x ,xxx);	ss.seekp(0);	ss << s;	cout << ss.str() << "\n";	}


As you can see, you have to jump through a few hoops, but it works. And to clarify, it inserts into the stream, but it does not push the contents forward, it simply overwrites them. It works the same way in console input as well.

- Drew
Heh, I know how to impliment it. Hell, I've already implimented it, but since I'm supposed to use the standard classes...

Anyways, if string has an insert and string stream doesn't, that's something at least.
Well, the filesystem and console implementations on most platforms don't permit insertion at an arbitrary position, so it would be conceptually very wrong if stringstreams suddenly did allow this - it would break the substitution principle (that is, derived classes should behave analoguosly to their bases) in a major way.

This topic is closed to new replies.

Advertisement