C++
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.
Exercise 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.
Show example solution
#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;
}
Exercise 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.
Show example solution
#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;
}
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.
Test yourself
-
Match each stream to its role
- istringstream
- Reading from string
- ostringstream
- Writing to string
- stringstream
- Both directions
- .str()
- Getting the string
-
Get the string with str()
std::string result = oss.____();
Show answer
std::string result = oss.str();
Next lesson: rvalue references