← C++ Index

🌊 <sstream> — String Streams — In-Memory I/O

Build strings using stream operators or parse strings like input streams. ostringstream is excellent for formatted string building; istringstream splits and parses strings easily.

Include: #include <sstream> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::istringstreamclass : istreamParse a string using stream extraction >>
std::ostringstreamclass : ostreamBuild a string using stream insertion <<
std::stringstreamclass : iostreamBidirectional string stream
oss.str()stringReturn the accumulated string
oss.str(s)voidReplace the internal buffer with s
oss.clear()voidClear error flags (does NOT clear buffer)
iss >> xistream &Extract next whitespace-delimited token
oss << xostream &Insert x into the string buffer

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

string make_label(const string &name, int score) {
    ostringstream oss;
    oss << name << " - " << score << " pts";
    return oss.str();
}

vector<string> split(const string &line, char delim = ',') {
    vector<string> tokens;
    istringstream iss(line);
    string tok;
    while (getline(iss, tok, delim)) tokens.push_back(tok);
    return tokens;
}

int main() {
    cout << make_label("Alice", 95) << "\n";
    cout << make_label("Bob",   87) << "\n";

    auto parts = split("apple,banana,cherry,date");
    for (auto &p : parts) cout << "  " << p << "\n";

    istringstream iss("42 3.14 hello");
    int i; double d; string s;
    iss >> i >> d >> s;
    cout << "int=" << i << " double=" << d << " str=" << s << "\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o sstream_demo sstream_demo.cpp

← <fstream>  |  🏠 Index  |  <memory> →