01 / 21

stringstream
for Parsing

Learn how to use C++ stringstream to break strings into tokens, extract typed data, and build powerful parsing routines from scratch.

C++

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.

Source Destination character flow keyboard, file, string variable, screen, file

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.

Manual Parsing
Track indices, compute lengths, handle edge cases yourself. Error-prone and verbose.
stringstream
Use >> to extract words and numbers automatically. Clean, readable, type-safe.

Setting Up stringstream

To use stringstream, include the <sstream> header. Then create a stringstream object, passing a string to its constructor.

C++ Setup
#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

Internal string buffer Alice   95   87.5 read pointer name = "Alice" score = 95 avg = 87.5 string int double Each >> call: 1. Skips whitespace 2. Reads token 3. Converts type 4. Advances pointer

Three Flavors of String Streams

istringstream
Input only. Read from a string using >>. Cannot write back to the stream.
ostringstream
Output only. Build a string using <<. Cannot read from the stream.
stringstream
Both. Read and write. The most flexible and commonly used variant.

>> 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

1
Include <sstream> at the top of your file.
2
Create a stringstream (or istringstream) from your input string.
3
Extract tokens using >> (whitespace) or getline(ss, token, delim) (custom delimiter).
4
Check the stream state: use a while loop that tests the stream as a boolean to detect when extraction fails or the stream is exhausted.
5
Process each token (store in a vector, convert, accumulate, etc.).

Example 1: Splitting Words

Split a sentence into individual words and store them in a vector.

C++ Code
#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.

C++ Code
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).

C++ Code
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.

C++ Code
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
10 + 20 + 30 + 40 + 50 = 150 Each >> extracts one int, adds to running total

Useful Methods: .str() and .clear()

ss.str()
Returns the current contents of the stream as a string. Also used to set new content: ss.str("new data").
ss.clear()
Resets the stream's error flags (eof, fail). Required after reaching the end if you want to reuse the stream.
Reusing a stringstream
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.

C++ Code
#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

✕ Forgetting .clear()
After EOF, new .str() data is loaded but extractions silently fail because the EOF flag is still set.
✕ Wrong Delimiter
Using >> on CSV data reads "red,green" as one token. Use getline(ss, tok, ',') for comma-separated input.
✕ Type Mismatch
Extracting into an int when the token is "hello" causes the stream to enter a fail state, stopping all further reads.

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

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

What does this program output?