Sign in to follow this  

Relatively simple iostream question

This topic is 4667 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
<< 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 ...

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4667 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this