stringstream in C++ and its Applications
A stringstream is a part of the C++ Standard Library, defined in the <sstream> header file. It allows us to read from and write to strings like they are streams.
It lets us take a string and extract data from it (like from cin), It also lets us build strings by inserting data into it (like into cout).
Types of String Streams
There are three types of string stream classes in C++:
Class | Purpose |
---|---|
stringstream | Both input and output |
istringstream | Input only (like cin) |
ostringstream | Output only (like cout) |
Uses or Applications of stringstream:
Convert String to Integer
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "123";
int num;
// Create a stringstream object initialized with 'str'
stringstream ss(str);
// Extract an integer from the stringstream and store it in 'num'
ss >> num;
cout << "Integer: " << num << endl;
return 0;
}
Output
Integer: 123
Convert Integer to String
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int num = 456;
string str;
//Create an empty stringstream object
stringstream ss;
// Insert the integer 'num' into the stringstream
// This converts the number into characters inside the stream
ss << num;
// Extract the contents of the stream as a string and store it in 'str'
ss>>str;
cout << "String: " << str << endl;
return 0;
}
Output
String: 456
Split a Sentence into Words
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string sentence = "C++ is powerful";
string word;
// Create a stringstream object initialized with the sentence
// This lets us read word by word like a stream
stringstream ss(sentence);
// Extract words from the stringstream one by one until no more words left
while (ss >> word) {
cout << word << endl;
}
return 0;
}
Output
C++ is powerful
Combine multiple values into a String
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int age = 25;
string name = "John";
// Create an empty stringstream object
stringstream ss;
// Insert multiple pieces of data (text, variables) into the stringstream
ss << "Name: " << name << ", Age: " << age;
// Get the combined string from the stringstream
string result = ss.str();
cout << result << endl;
return 0;
}
Output
Name: John, Age: 25
Resetting or Clearing a stringstream
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
// Put some data into the stringstream
ss << "Hello, world!";
cout << "Before clearing: " << ss.str() << endl;
// Clear the contents of the stringstream
ss.str("");
// Reset the stringstream's state flags (like eof, fail)
ss.clear();
// Now we can reuse the stringstream for new data
ss << "New data here!";
cout << "After clearing and reuse: " << ss.str() << endl;
return 0;
}
Output
Before clearing: Hello, world! After clearing and reuse: New data here!