C++ String Streams

Introduction

There is a stream that allows us to read from and write to a string.

It is defined inside the <sstream> header, and there are three different string streams:

  • std::stringstream - the stream to read from a string
  • std::otringstream - the stream to write to a string
  • std::stringstream - the stream to both read from and write to a string

To create a simple string stream, we use:

#include <sstream> 

int main() 
{ 
    std::stringstream ss; 
} 

This example creates a simple string stream using a default constructor.

To create a string stream and initialize it with a string literal, we use:

#include <iostream> 
#include <sstream> 

int main() /*from ww w .ja va 2  s  .co  m*/
{ 
    std::stringstream ss{ "Hello world." }; 
    std::cout << ss.str(); 
} 

Here we created a string stream and initialized it with a string literal in a constructor.

Then we used the string stream's .str() member function to print the content of the stream.

The .str() member function gets the string representation of the stream.




PreviousNext

Related