简体   繁体   中英

How to insert a string to the beginning of a stringstream

For example only and not the actual code:

stringstream ss;
ss << " world!";

string hello("Hello");

// insert hello to beginning of ss ??

Thanks for all the responses, I also found this code, which works:

ostringstream& insert( ostringstream& oss, const string& s )
{
  streamsize pos = oss.tellp();
  oss.str( s + oss.str() );
  oss.seekp( pos + s.length() );
  return oss;
}

You cannot do it without making at least one copy. One way:

std::stringstream ss;
ss << " world!";

const std::string &temp = ss.str();
ss.seekp(0);
ss << "Hello";
ss << temp;

This relies on the "most important const " to extend the lifetime of the temporary and avoid making an extra copy.

Or, simpler and possibly faster:

std::stringstream ss;
ss << " world!";

std::stringstream temp;
temp << "Hello";
temp << ss.rdbuf();
ss = std::move(temp); // or ss.swap(temp);

This borrows the rdbuf approach from this answer , since the interesting problem here is how to minimize copies.

the only way i can see is to create the string from stream and prefix your other string

string result = hello + ss.str();

its called a stream for a reason.

Assuming ss1 contains "hello"

ss1 << ss.rdbuf();

or

ss1 << "hello" << ss;

Refer this URL for more info:-

stringstream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM