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 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::istringstream | class : istream | Parse a string using stream extraction >> |
| std::ostringstream | class : ostream | Build a string using stream insertion << |
| std::stringstream | class : iostream | Bidirectional string stream |
| oss.str() | string | Return the accumulated string |
| oss.str(s) | void | Replace the internal buffer with s |
| oss.clear() | void | Clear error flags (does NOT clear buffer) |
| iss >> x | istream & | Extract next whitespace-delimited token |
| oss << x | ostream & | Insert x into the string buffer |
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