strstream Class- A stringstream associates a string object with a stream that allows us to read from the string as if it were a stream (like cin). This class describes an object that controls insertion and extraction of elements and encoded objects using a stream buffer of class strstreambuf. Stringstream class is extremely useful in parsing input.
The Stringstream has different methods. These are like below %u2212
clear(): Used to clear the stream
str(): To get and set the string object whose content is present in stream
operator << : This will add one string into the stringstream
operator >> : This is used to read from a stringstream object.
This class has 4 member functions. They are:
Thus the function str of stringstrream returns the pointer to the beginning of the buffer, after freezing it and effectively calls rdbuf() -> str().
char* str() ;
This function accepts a string object, whose content is copied.
It returns a string object with a copy of the current contents in the stream buffer i.e a pointer to the beginning of the buffer in the associated std::strstreambuf or a null pointer if no buffer is available.
Before a call to str() that uses the result as a C string, the stream buffer must be null-terminated. Regular output such as with stream << 1.2 does not store a null terminator, it must be appended explicitly, typically with the manipulator std::ends.
After a call to str(), dynamic streams become frozen. A call to freeze (false) is required before exiting the scope in which this strstream object was created. Otherwise the destructor will leak memory. Also, additional output to a frozen stream may be truncated once it reaches the end of the allocated buffer, which may leave the buffer not null-terminated.
Basic Guarantee- The object is in a valid state, if an exception is thrown.
Accesses form 1 or modifies form 2 the stringstream object. Concurrent access to the same object may cause data races.
Program 1: Example of stringstream::str function:
using namespace std;
int main ()
ss.str (" Welcome to cppsecrets ");
std::string s = ss.str();
std::cout << s << '\n';
Output: Welcome to cppsecrets