istringstream
- C++ course
- Intermediate
- Lesson 94/116
- 5 min
Learn to read from strings with istringstream.
Parsing with istringstream
std::istringstream lets you read data from a string. It works like a file stream but the data source is an in-memory string.
It comes from the #include <sstream> header. Example: std::string data = "10 20"; std::istringstream iss(data); int a, b; iss >> a >> b;. Here the iss stream reads from the data string and >> extracts numbers in order. This is very practical for splitting a line into parts or processing user input. All the rules of the >> operator from file reading apply here too.
Extracting from a string with >>
The >> operator on an istringstream pulls whitespace-separated pieces from the string in order. Each extraction reads up to the next space.
Example: std::istringstream iss("apple pear banana"); std::string a, b, c; iss >> a >> b >> c;. Here a becomes "apple", b "pear", c "banana". The same method reads numbers: "10 20" in a string becomes two integers. When the stream ends, >> fails and the variable is unchanged.
Practice Extract numbers from a string and sum them
The starting code has a data string containing "10 20 30". Use std::istringstream to extract three numbers from it, sum them and print the total with std::cout.
Starter code
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string data = "10 20 30";
// Extract the numbers and sum them
return 0;
}Sample solution
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string data = "10 20 30";
std::istringstream iss(data);
int a, b, c;
iss >> a >> b >> c;
std::cout << a + b + c;
return 0;
}Expected output
60
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Define an istringstream
std::____ iss(data);
std::istringstream iss(data);
Explanation: std::istringstream reads from a string.
2 What source does istringstream read from?
std::istringstream iss("10 20");- A file
- The keyboard
- An in-memory string Correct answer
- The network
Explanation: istringstream reads from an in-memory string.
3 Match each piece to its role
| Term | Meaning |
|---|---|
istringstream |
Reading from a string |
>> |
Data extraction |
#include <sstream> |
Header file |
iss(data) |
Initializing the stream |