CodeBlanks Logo Icon CodeBlanks

ostringstream

Learn to write to strings with ostringstream.

Building a string with ostringstream

std::ostringstream builds a string by combining pieces. You write strings, numbers and variables in sequence with the << operator.

Example: std::ostringstream oss; oss << "Age: " << 25;. Here the oss stream receives the string "Age: " then the number 25. You get the resulting string with oss.str(): std::string result = oss.str(); gives "Age: 25". This is the clean way to gather multiple pieces into one string; it is more flexible than concatenating manually with +.

Getting the string with str()

The .str() method returns all data written to an ostringstream as a single string. You can use this string anywhere.

Example: oss << "Name: " << name << " Age: " << age; std::cout << oss.str();. This combines four pieces and prints them. The .str() call does not change the stream content; you can call it as many times as you want. To clear the stream you write oss.str("");. This flexibility makes ostringstream a powerful tool for everyday output formatting.

Practice Build a string and print it

Create a std::ostringstream. Write the string "Result: " and the number 42 with <<. Get the resulting string with .str() and print it with std::cout.

Starter code

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

int main() {
    // Build the string and print it

    return 0;
}

Sample solution

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

int main() {
    std::ostringstream oss;
    oss << "Result: " << 42;
    std::cout << oss.str();
    return 0;
}

Expected output

Result: 42

Questions and answers

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

1 Match each piece to its role

Term Meaning
ostringstream Writing to a string
<< Data writing
.str() Getting the string
oss << 42 Writing a number

2 Complete the str() call

Question
std::string result = oss.____();
Answer
std::string result = oss.str();

Explanation: .str() returns the stream's string.

3 What does ostringstream oss; oss << 42; oss.str() return?

main.cpp
std::ostringstream oss;
oss << 42;
oss.str();
  • "oss"
  • 42
  • '4'
  • "42" Correct answer

Explanation: str() returns the number as a string: "42".

All lessons in Intermediate