Table of Contents
String streams allow input and output operations to be performed on strings instead of the keyboard or console. They are provided by the <sstream> library and use the same stream operators (<< and >>) as other C++ streams.
The std::stringstream class can both write data to a string and read data from it. String streams are commonly used for parsing text, formatting data, and converting between strings and other data types.
Source Code #
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss;
ss << "Age: " << 25;
std::string text = ss.str();
std::cout << text << '\n';
return 0;
}
Output #
Age: 25
Explanation #
#include <sstream>includes the Standard Library header that provides string stream classes.std::stringstreamcreates a stream that stores its data in a string.- The stream insertion operator (
<<) writes data into the string stream in the same way it writes tostd::cout. ss.str()returns the contents of the string stream as astd::string.- The returned string is stored in the variable
text. std::coutdisplays the string stored in the string stream.- String streams are commonly used for formatting text, parsing input, and converting between strings and numeric data types.
return 0;terminates the program successfully.