CodeBlanks Logo Icon CodeBlanks

Summary - Stringstream

Combine istringstream and ostringstream to write a CSV parser.

Summary - Stringstream

In this group you learned string streams. istringstream reads from a string, ostringstream writes to a string, stringstream does both.

For type conversion you turn a string into a number with istringstream and a number into a string with ostringstream. For formatting you use std::fixed and std::setprecision. Now you will consolidate what you learned with two tasks: first parsing numbers from a string, then formatting a number.

Practice Extract numbers from a string and sum them

The starting code has a data string containing "5 10 15". Extract three numbers with std::istringstream, sum them and print the total with std::cout.

Starter code

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

int main() {
    std::string data = "5 10 15";
    // Extract the numbers and sum them

    return 0;
}

Sample solution

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

int main() {
    std::string data = "5 10 15";
    std::istringstream iss(data);
    int a, b, c;
    iss >> a >> b >> c;
    std::cout << a + b + c;
    return 0;
}

Expected output

30

Practice Format a number into a string

The starting code has a pi variable of 3.14159. Format pi with std::ostringstream using std::fixed and std::setprecision(2). Get the string with .str() and print it with std::cout.

Starter code

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

int main() {
    double pi = 3.14159;
    // Format pi to two decimals and print

    return 0;
}

Sample solution

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

int main() {
    double pi = 3.14159;
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(2) << pi;
    std::cout << oss.str();
    return 0;
}

Expected output

3.14

End of section

You completed string streams. You can now read from a string with istringstream, write to a string with ostringstream and use both directions with stringstream.

String streams are powerful tools for type conversion and formatting. The next groups cover advanced topics like move semantics and operator overloading. The stream concept you learned is common to both file and string operations; that makes it very valuable.

Questions and answers

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

1 Match each stream to its role

Term Meaning
istringstream Reading from string
ostringstream Writing to string
stringstream Both directions
.str() Getting the string

2 Get the string with str()

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

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

All lessons in Intermediate