utkarsh9's blog

By utkarsh9, history, 6 weeks ago, In English

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin).

stringstream provides different methods:

clear() : to clear the stream

str() : to get and set string object whose content is present in stream.

operator << : add a string to the stringstream object.

operator >> : read content from the stringstream object,

You can construct a stringstream by passing the string for which you want to use it.

Then you can use stringstream for reading data exactly the way you would use cin. stringstream class is extremely useful in parsing input.

Applications of stringstream :

1. Extract individual words from a sentence or paragraph.

A sentence or a paragraph generally consists of a large number of words and sometimes we want to work on individual words present in the sentence. In that case we can use stringstream to extract words from a complete sentence.

#include <bits/stdc++.h>; 
using namespace std; 

int main() 
{ 
    string str= "Welcome to coding with art";
    
    stringstream ss(str);       // declare stringstream for string str
    string word;      
    vector<string> words;  
    int wordcount = 0;
    while(ss >> word){
        words.push_back(word);
        wordcount++;
    }
    cout<<"No of words : "<< wordcount <<"\n";
    for(string word : words)
        cout<<word<<"\n";
    return 0; 
} 

Output :

No of words : 5
Welcome
to
coding
with
art

2. Extract words from a sentence with custom separator (Tokenizing a string)

Sometimes you may be given a string which contains a different separator than " "(spaces). In that case it becomes more difficult to tokenize the string into separate words. But using stringstream with getline() function allows us to do this very easily.

Read the complete article with all the applications here : STRINGSTREAM IN C++ : DETAILED USAGE AND APPLICATIONS WITH EXAMPLES

 
 
 
 
  • Vote: I like it
  • +32
  • Vote: I do not like it