CodeBlanks Logo Icon CodeBlanks

stringstream

Learn bidirectional streams with stringstream.

stringstream in both directions

std::stringstream is used for both reading and writing. It combines the capabilities of istringstream and ostringstream.

Example: std::stringstream ss; ss << "100 200"; int a, b; ss >> a >> b;. Here we first write a string to the stream with <<, then extract the numbers back with >>. This is one tool for the build-a-string-then-parse pattern. The #include <sstream> header suffices. You can get the written content with .str() and set the content to read with .str("...").

The write-then-read pattern

The most common use of stringstream is: first write data with <<, then read it back with >>. This is a practical way to serialize and parse data.

Example: ss << name << " " << age; builds a record. Then ss >> name2 >> age2; reads it back. This pattern is the basis of save and load operations. To reset the content you write ss.clear(); ss.str("");; clear() resets error flags and str("") empties the content.

Practice Write to the stream and read back

Create a std::stringstream. Write "100 200" with <<. Then extract two numbers with >>, sum them and print the total with std::cout.

Starter code

main.cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
    // Write to the stream, read back and sum

    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::stringstream ss;
    ss << "100 200";
    int a, b;
    ss >> a >> b;
    std::cout << a + b;
    return 0;
}

Expected output

300

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What can stringstream do?

main.cpp
std::stringstream ss;
  • Read only
  • Write only
  • Both read and write Correct answer
  • Open files only

Explanation: stringstream can both read and write.

2 Define a stringstream

Question
std::____ ss;
Answer
std::stringstream ss;

Explanation: std::stringstream is a bidirectional stream.

3 Match each piece to its role

Term Meaning
stringstream Bidirectional stream
<< Writing to stream
>> Reading from stream
.clear() Flag reset

All lessons in Intermediate