C++
String streams
Learn string streams with std::istringstream and ostringstream.
String streams: istringstream
Sometimes you need to pull numbers or words out of a string piece by piece. C++ offers the istringstream stream for this; you can read a string with the >> operator just like cin.
#include <sstream>
istringstream iss("10 20 30");
int a, b, c;
iss >> a >> b >> c;
Here the iss object treats the string as a stream; three int values are extracted in order. Whitespace is skipped automatically. This approach is especially handy for parsing space-separated data.
Formatting with ostringstream
On the other hand, ostringstream is used to combine many pieces into a single string. You write values into the stream with the << operator, then call .str() to get the whole stream as a string.
ostringstream oss;
oss << "Score: " << 95;
string result = oss.str();
Here the result string becomes "Score: 95". This lets you combine values of different types without juggling to_string; it is especially useful when building error messages or reports.
Exercise Read two numbers from a string and add them
Add the #include <sstream> header. Create a read stream with istringstream iss("15 25");. Pull the numbers into two int variables with the >> operator, then print their sum with cout.
Show example solution
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
istringstream iss("15 25");
int a, b;
iss >> a >> b;
cout << a + b << endl;
return 0;
}
Test yourself
-
Which is suitable for reading space-separated numbers from a string?
- istringstream
- ostringstream
- to_string
- stoi
Show answer
istringstream — istringstream uses the string as a read stream.
-
Fill in the blank: ostringstream declaration
#include <sstream>
using namespace std;
int main() {
____ oss;
oss << "Hello";
return 0;
}
Show answer
#include <sstream>
using namespace std;
int main() {
ostringstream oss;
oss << "Hello";
return 0;
}
-
Match each stream type with its job
- istringstream
- Reads from a string
- ostringstream
- Writes to a string
- .str()
- Returns stream as a string
Next lesson: stoi and stod