Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to apply the stringstream class in C++

Saad Akbar

stringstream in C++ enables a string to be read by connecting a string object as if it were a stream. It is similar to the cin operator for taking inputs.

Note: We need to include the sstream header file to use stringstream.

Functions in stringstream

  • >>: It reads from the stringstream object.
  • <<: It concatenates the string by adding a string to the stringstream object.
  • clear(): It empties the stream.
  • str(): It retrieves or assigns a stringstream object that is present in the stream.

Example

#include <iostream>
#include <sstream>
#include<string>
using namespace std;
 
int WordCounter(string s)
{
  //Initializing the counter
  int counter = 0;
    // Breakdown of the input into words using 
    // stringstream
   
    // Storing independent words
    string w;
   
    // Breaking words
    stringstream x(s);
 
    
    while (x >> w)
        counter++;
    return counter;
}
 

int main()
{
    string sample = "Educative for learning "
              ;
    cout << " Word Count: " << WordCounter(sample);
    return 0;
}
Program to get the word count of a string

Explanation

  • Lines 1 to 13: We include the header files, give the function name, and initialize the counter variable to 0.
  • Line 14: We declare a string variable to store the individual words.
  • Line 17: We declare a stringstream object to break the string into words.
  • Lines 20 to 22: A while loop iterates until all the words from the stream are stored in the string. Meanwhile, the counter increments with each iteration to count the total words and, eventually, return them.
  • Lines 28 to 30: We declare a string containing some text, and then print the word count of the string.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring