• Home
  • 2.15 String Streams

2.15 String Streams

View Categories

2.15 String Streams

1 min read

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::stringstream creates 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 to std::cout.
  • ss.str() returns the contents of the string stream as a std::string.
  • The returned string is stored in the variable text.
  • std::cout displays 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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *