Parsing input using stringstream in C++

Revision en5, by utkarsh9, 2020-10-21 10:25:02

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

Tags #c++, stringstream, input, parsing

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English utkarsh9 2020-10-21 10:25:02 65
en4 English utkarsh9 2020-10-21 06:12:04 410 Tiny change: 'nce.\n\n\n#include <' -> 'nce.\n\n\n/#include <'
en3 English utkarsh9 2020-10-21 06:01:39 65
en2 English utkarsh9 2020-10-21 06:00:33 34
en1 English utkarsh9 2020-10-21 05:59:08 1751 Initial revision (published)