String streams
- C++ course
- Beginner
- Lesson 88/116
- 5 min
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.
Practice 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.
Starter code
#include <iostream>
#include <string>
// add the sstream header
using namespace std;
int main() {
// use istringstream to read two numbers from "15 25"
// print their sum with cout
return 0;
}Sample 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;
}Expected output
40
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is suitable for reading space-separated numbers from a string?
- istringstream Correct answer
- ostringstream
- to_string
- stoi
Explanation: istringstream uses the string as a read stream.
2 Fill in the blank: ostringstream declaration
#include <sstream>
using namespace std;
int main() {
____ oss;
oss << "Hello";
return 0;
}
#include <sstream>
using namespace std;
int main() {
ostringstream oss;
oss << "Hello";
return 0;
}
Explanation: ostringstream creates a writing stream.
3 Match each stream type with its job
| Term | Meaning |
|---|---|
istringstream |
Reads from a string |
ostringstream |
Writes to a string |
.str() |
Returns stream as a string |