c++ stringstream tutorial code example

Example 1: stringstream tutorial

#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;
}

Example 2: stringstream in c++

- A stringstream associates a string object with a stream allowing 
you to read from the string as if it were a stream (like cin).
- Method:
 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 something from the stringstream object,

Example 3: stringstream in c++

std::stringstream os;
os << "12345 67.89"; // insert a string of numbers into the stream

std::string strValue;
os >> strValue;

std::string strValue2;
os >> strValue2;

// print the numbers separated by a dash
std::cout << strValue << " - " << strValue2 << std::endl;

Tags:

Cpp Example