Stringstream input and output

Stringstream

Stringstream performs input and output operations on a memory stream. Stringstream is defined in a <sstream> header. Stringstream treats string as a memory stream. It is used for various type conversions or string formatting.

Input

For the input we use the std::istringstream. We insert data into a stream using the stream insertion << operator. Example:

#include <iostream>
#include <sstream>
int main(){
	std::istringstream ss;
	ss << "Insert this text.";
	std::cout << ss.str();
}

We can insert values of different types into a stringstream:

#include <iostream>
#include <sstream>
int main(){
	std::istringstream ss;
	int x = 123;
	char c = 'A';
	double d = 456.78;
	ss << x << c << d;
	std::cout << ss.str();
}

We can initialize the istringstream with a string:

#include <iostream>
#include <string>
#include <sstream>
int main(){
	std::string mystring = "Hello World";
	std::istringstream ss(mystring);
	std::cout << ss.str();
}

Output

For output we use the std::ostringstream. We output data from a stringstream using the stream extraction >> operator:

#include <iostream>
#include <string>
#include <sstream>
int main(){
	std::string mystring = "123 456.789 A";
	std::ostringstream ss(mystring);
	int x;
	double d;
	char c
	ss >> x >> d >> c;
	std::cout << "x: " << x << " d: " << d << " c: " << c;
}

We can also use the std::stringstream for both input and output.