stringstream
for Parsing
Learn how to use C++ stringstream to break strings into tokens, extract typed data, and build powerful parsing routines from scratch.
What Is a Stream?
In C++, a stream is an abstraction for a sequence of characters flowing from a source to a destination. You already use streams every time you write cin or cout.
Why Use stringstream?
Raw string methods like find() and substr() work, but they require manual index tracking. A stringstream gives you the same convenient extraction operator (>>) you use with cin, applied to any string.
Setting Up stringstream
To use stringstream, include the <sstream> header. Then create a stringstream object, passing a string to its constructor.
#include <iostream> #include <sstream> // Required header #include <string> using namespace std; int main() { string data = "Alice 95 87.5"; stringstream ss(data); // Create stream from string string name; int score; double avg; ss >> name >> score >> avg; // Extract typed data cout << name << ": " << score << ", " << avg; return 0; }
How Extraction Works
Three Flavors of String Streams
>> vs getline()
| >> (extraction) | getline(ss, var, delim) | |
|---|---|---|
| Delimiter | Whitespace (space, tab, newline) | Any character you choose |
| Skips leading spaces? | Yes | No |
| Type conversion? | Automatic | Always reads a string |
| Best for | Space-separated tokens | CSV, custom delimiters |
How to Parse Step by Step
Example 1: Splitting Words
Split a sentence into individual words and store them in a vector.
#include <sstream> #include <vector> #include <string> vector<string> splitWords(const string& line) { istringstream ss(line); vector<string> words; string word; while (ss >> word) { // Reads until stream is empty words.push_back(word); } return words; }
Example 2: Parsing CSV Data
Parse a comma-separated line using getline with a custom delimiter.
string csv = "red,green,blue,yellow"; istringstream ss(csv); string color; while (getline(ss, color, ',')) { cout << color << endl; } // Output: // red // green // blue // yellow
Example 3: Type Conversion
Extract mixed types from a single string: a name (string), an age (int), and a GPA (double).
string record = "Bob 17 3.85"; istringstream ss(record); string name; int age; double gpa; ss >> name >> age >> gpa; cout << name << " is " << age << " with GPA " << gpa << endl; // Output: Bob is 17 with GPA 3.85
Example 4: Summing Numbers in a String
Given a string of space-separated integers, compute their sum.
string nums = "10 20 30 40 50"; istringstream ss(nums); int val, total = 0; while (ss >> val) { total += val; } cout << "Sum: " << total << endl; // Output: Sum: 150
Useful Methods: .str() and .clear()
stringstream ss("42"); int x; ss >> x; // x = 42, stream reaches EOF ss.clear(); // Reset error/EOF flags ss.str("99"); // Load new string ss >> x; // x = 99
Building Strings with ostringstream
Use ostringstream to assemble a formatted string from multiple pieces, just like writing to cout.
#include <sstream> ostringstream oss; string name = "Alice"; int score = 95; oss << name << " scored " << score << " points"; string result = oss.str(); // result == "Alice scored 95 points"
Common Mistakes
Summary Reference
| Operation | Syntax | Purpose |
|---|---|---|
| Create stream | istringstream ss(str) | Wrap a string for reading |
| Extract token | ss >> var | Read next whitespace-delimited token |
| Custom delimiter | getline(ss, var, ',') | Read up to a specific character |
| Get string | ss.str() | Return stream contents as string |
| Set new data | ss.str("new") | Replace internal buffer |
| Reset flags | ss.clear() | Clear eof/fail flags |
| Check state | if (ss.fail()) | Detect extraction errors |
Question 1 of 5
Which header file is required to use stringstream in C++?
Question 2 of 5
string data = "100 200 hello"; istringstream ss(data); int a = 0, b = 0, c = 0; ss >> a >> b >> c; cout << a << " " << b << " " << c;
What happens when this code runs?
Question 3 of 5
To parse the string "apple,banana,cherry" into three separate tokens, which approach is correct?
Question 4 of 5
After a stringstream reaches the end of its buffer (EOF), what must you do before loading new data with .str()?
Question 5 of 5
string line = "5 10 15 20";
istringstream ss(line);
int num = 0, sum = 0;
while (ss >> num) {
sum += num;
}
cout << sum;
What does this program output?