stringstream code example

Example 1: convert string to stream c++

// stringstream::str
#include <string>       // std::string
#include <iostream>     // std::cout
#include <sstream>      // std::stringstream, std::stringbuf

int main () {
  std::stringstream ss;
  ss.str ("Example string");
  std::string s = ss.str();
  std::cout << s << '\n';
  return 0;
}

Example 2: 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 3: how to parse using stringstream

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

Example 4: c++ string to stream

// EXAMPLE
ostringstream ssTextAsStream("This is part of the stream."); // declare ostringstream
string sTextAsString = ssTextAsStream.str(); // converted to string
cout << sTextAsString << "\n"; // printed out

/* SYNTAX
<YourStringStream>.str()
*/

/* HEADERS
#include <iostream>
#include <sstream>
using namespace std;
*/

Example 5: 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