string stream in c++ code example
Example 1: 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 2: 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 3: c++ string to stream
ostringstream ssTextAsStream("This is part of the stream.");
string sTextAsString = ssTextAsStream.str();
cout << sTextAsString << "\n";
Example 4: stringstream in c++
std::stringstream os;
os << "12345 67.89";
std::string strValue;
os >> strValue;
std::string strValue2;
os >> strValue2;
std::cout << strValue << " - " << strValue2 << std::endl;