Introduction
In C++, there are frequent situations where you want to convert numbers to strings, convert strings to numbers, or split a space-separated string into individual words. By using “String Streams” provided by the standard library <sstream> header, you can achieve these tasks using the exact same intuitive syntax as cout and cin with the << / >> operators.
In this article, I will explain the usage of the two main string stream classes:
- std::ostringstream: Used for writing (formatting) various data into a string.
- std::istringstream: Used for reading (parsing) a string to decompose it into various data types.
1. std::ostringstream: Constructing (Writing) Strings
ostringstream (output string stream) appends various data (numbers, strings, etc.) passed via the << operator into an internal string buffer. Finally, calling the .str() member function allows you to retrieve the constructed std::string.
Sample Code
#include <iostream>
#include <sstream> // String streams
#include <string>
using namespace std;
int main() {
ostringstream oss;
string item = "Apple";
int price = 120;
int count = 3;
// 1. Write data of various types to the stream using the << operator
oss << "Item: " << item
<< ", Price: " << price << " yen"
<< ", Qty: " << count
<< ", Total: " << price * count << " yen";
// 2. Retrieve the constructed string with .str()
string result = oss.str();
cout << result << endl;
return 0;
}
Execution Result
Item: Apple, Price: 120 yen, Qty: 3, Total: 360 yen
2. std::istringstream: Decomposing (Reading) Strings
istringstream (input string stream) is created based on an existing string. Using the >> operator, you can extract data separated by spaces or newlines into variables one by one, just as if you were reading from cin.
Sample Code
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string source_data = "Sato 35 Development";
// 1. Initialize istringstream with the string you want to read
istringstream iss(source_data);
string name, department;
int age;
// 2. Read space-separated data into variables sequentially using the >> operator
iss >> name >> age >> department;
// 3. Verify the read results
cout << "Name: " << name << endl;
cout << "Age: " << age << " years old" << endl;
cout << "Dept: " << department << endl;
return 0;
}
Execution Result
Name: Sato
Age: 35 years old
Dept: Development
Summary
In this article, I explained the basic usage of string streams in C++.
- ostringstream: Used to construct a single formatted string by combining data of various types.
- istringstream: Used to decompose a string separated by spaces or other delimiters into individual data pieces.
- stringstream: There is also a class that can handle both reading and writing with a single object.
By mastering string streams, you can write complex string formatting and parsing processes safely and concisely using the intuitive interface common to cout and cin.
