Stringstream in C++ and its applications
In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application.
What is stringstream?
With the aid of a stringstream, user can read from a string object as though it were a stream (like cin). sstream header file inclusion is required in order to use stringstream. Input parsing benefits greatly from the use of the stringstream class.
Common techniques are:
- clear() - It is used to empty the stream.
- str() – It can be used to retrieve and modify string objects with content that is present in the stream.
- operator << - To the stringstream object, add a string.
- operator >> - Read from the stringstream object using the operator >>.
Let's look at two string stream examples in below.
Example 1: We will separate the words into individual strings in this program.
C++ Code:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string str (" Hey Mr. don't move ");
// declaring a string that will be used to preserve word each time.
string abc;
// Using a string stream to separate input into words
stringstream str_strm ( str );
// Considering a vector that can contain our words.
vector < string > splt;
// Using while loop
while ( str_strm >> abc )
{
// pushing in abc
splt.push_back ( abc );
}
// using for loop
for ( int index = 0; index < splt.size(); index ++ )
cout << splt [ index ] << endl;
}
Output:
Hey
Mr.
don't
move
Example 2: The total number of words in a given string will be determined by this program.
C++ Program:
#include <iostream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int cntw ( string str )
{
//Using a string stream to separate input into words
stringstream a ( str );
// declaring a string that will be used to preserve words individually
string www;
// declaring a variable to keep counts of words
int ct = 0;
// using while loop
while ( a >> www )
ct ++;
return ct;
}
// main function
int main ()
{
string a = " My dream is to be a successful Technical Content Developer";
cout << " The total number of words are: " << cntw ( a );
return 0;
}
Output:
The total number of words are: 10
From the above two programs, we learn how to utilize stringstream in a C++ Code.