Stringstream in C++

C++Server Side ProgrammingProgramming

Here we will see the string stream in C++. The string stream associates a string object with a string. Using this we can read from string as if it were a stream like cin.

The Stringstream has different methods. These are like below −

clear(): Used to clear the stream

str(): To get and set the string object whose content is present in stream

operator << : This will add one string into the stringstream

operator >> : This is used to read from stringstream object.

Let us see two examples of string streams. In the first program we will divide the words into separate strings.

Example

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
   string str("Hello from the dark side");
   string tmp; // A string to store the word on each iteration.
   stringstream str_strm(str);
   vector<string> words; // Create vector to hold our words
   while (str_strm >> tmp) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }
   for(int i = 0; i<words.size(); i++)
      cout << words[i] << endl;
}

Output

Hello
from
the
dark
side

Here we will convert Decimal to Hexadecimal using string stream.

Example

#include<iostream>
#include<sstream>
using namespace std;
main(){
   int decimal = 61;
   stringstream my_ss;
   my_ss << hex << decimal;
   string res = my_ss.str();
   cout << "The hexadecimal value of 61 is: " << res;
}

Output

The hexadecimal value of 61 is: 3d
raja
Published on 07-May-2019 15:05:54
Advertisements