// A stringstream is a stream, like cout or cin, except that it’s attached // to a string, rather than being attached to a file or a terminal. // // Write/insert (<<) to an ostringstream. // Read/extract (>>) from an istringstream. // // Here are a few simple stringstream examples. #include // For cout & cerr #include // For hex, setw, setfill #include // For istringstream & ostringstream #include // For the time of my life using namespace std; int main() { // Convert int to string ostringstream oss; int n = 8675309; oss << n; // Insert the int into the stream string s = oss.str(); // What got “printed” to the stream? cout << n << " becomes " << s << '\n'; // Convert string to double s = "+123.4560"; istringstream iss(s); // Initialize istringstream with the string double d; if (iss >> d) // Try to extract a double from the stream cout << s << " becomes " << d << '\n'; else cerr << "Error: can’t convert " << s << "\n"; // Convert int to hex string oss.str(""); // Reset to nothing oss << setw(4) << setfill('0') << hex << 20; s = oss.str(); // What got “printed” to the stream? cout << "Result is “" << s << "”\n"; }