user88637
user88637

Reputation: 12150

Is there a way to use an "ostream" to write over an existing instance of std::string

I know all kinds of ostreams holds their own internal buffers. I have to know whether there is some kind of ostream which accept an instance std::string and write on that instance.

(I want to avoid redundant copies)

Note: My question is about the standard library, don't offer me other libraries that can do that, I know they exist. :)

Edit: After a request to be more specific ... Here is what I want, consider the following code:

std::string str = "bla bla bla ";
std::ospecialstream o(str);
o << 34 << " bla bla";
std::cout << str; //console output : "bla bla bla 34 bla bla"

I want ospecialstream such that it won't copy str contents into some internal buffer but rather write to the same instance of str.

Edit #2 I need it for performece reasons , ostringstream will make a memcopy when created with a string and will also make a memcpy when the contents are retrieved.

Upvotes: 2

Views: 325

Answers (4)

ackb
ackb

Reputation: 592

#include <iostream>
#include <string>

class intostring : public std::basic_streambuf<char> {
  std::string &str;
public:
  intostring(std::string &pstr):str(pstr) {}
  virtual std::streamsize xsputn(const char *const p, const std::streamsize n) {
    str.append(p, n);  
  }
};

int main() {
  std::string s("Original string: ");

  intostring newbuf(s);

  std::streambuf *oldbuf = std::cout.rdbuf(&newbuf);
  std::cout << "Should go to string" << std::endl;
  std::cout.rdbuf(oldbuf);  

  std::cout << "Should go to console again ... and here's the string: '" 
            << s << "'" << std::endl;
}

Outputs:

Should go to console again ... and here's the string: 'Original string: Should go to string'

Upvotes: 1

eidolon
eidolon

Reputation: 3403

Short answer: no

Long answer: Yes, but this requires writing your own streambuf class, which you then set with rdbuf. Also, now deprecated strstream does almost what you want and may still be in your compiler libraries.

Upvotes: 1

dirkgently
dirkgently

Reputation: 111316

std::ostringstream part of sstream header.

How about this:

void appendStuff(string& in) {
   ostringstream os;
   os << 34 << " bla bla";
   in += os.str();
}

Upvotes: 3

anon
anon

Reputation:

If you are asking can you alter the buffering of ostreams, then the answer is yes. However, depending on what you actually want the buffer to do, this is not a particularly simple task. You will want to consult a book like Langer & Kreft for more info.

L&K have an example of how to implement an unbuffered output stream - it begins on page 229 of the book. It's too long to reproduce here, but basically you need to redefine the overflow() method of a derived streambuf class.

Note the book is not available on-line but the source code apparently is - see this page for details.

Upvotes: 2

Related Questions