Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how copy from one stringstream object to another in C++?

I have std::stringstream object ss1. Now, I would like to create another copy from this one.

I try this:

std::stringstream ss2 = ss1; 

or:

std::stringstream ss2(ss1) 

neither works

The error message is like this:

std::ios::basic_ios(const std::ios &) is not accessible from bsl::basic_stringstream, bsl::allocator>::basic_stringstream(const bsl::basic_stringstream, bsl::allocator>&).

like image 922
skydoor Avatar asked Aug 09 '10 17:08

skydoor


People also ask

Can we use Stringstream in C?

How to Perform Extraction or Read Operation in StringStream in C++ Like the insertion, we can also perform extraction on StringStream in C++, like the cin >> operator. We can again do this by using the >> operator or the str() function.

Can you return a Stringstream?

You can't return a stream from a function by value, because that implies you'd have to copy the stream.

What is the difference between string and Stringstream?

Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.

How does Stringstream C++ work?

The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.


1 Answers

Indeed, streams are non-copyable (though they are movable).

Depending on your usage, the following works quite well:

#include <iostream> #include <sstream>  int main() {     std::stringstream ss1;     ss1 << "some " << 123 << " stuff" << std::flush;      std::stringstream ss2;     ss2 << ss1.rdbuf(); // copy everything inside ss1's buffer to ss2's buffer      std::cout << ss1.str() << std::endl;     std::cout << ss2.str() << std::endl; } 

Output:

some 123 stuff
some 123 stuff

like image 126
GManNickG Avatar answered Oct 06 '22 20:10

GManNickG