In C++, stringstreams are streams that extract input from a string (as opposed to the keyboard cin or a file). To use in our programs, we must #include <sstream>.

They’re useful when input must be processed one line at a time. This allows our program to take in an entire line of input, analyse it, and process accordingly by deciding if the input is valid or not.

A potentially good idea is to create a new string stream handler sin and so the following:

stringstream sin(inputLine);

Methods

The getline() method inputs the entire line from the IO stream. Take an example:

#include <string>
#include <iostream>
#include <sstream>
 
int main () {
	string inputLine;
	int a; float b;
	getline(cin, inputLine);
	// EITHER
	stringstream ss(inputLine);
	// OR ALTERNATIVELY
	stringstream ss;
	ss << inputLine;
	// END
	ss >> a;
	// error checking and handling
	ss >> b;
 
	return 0;
}

This is especially useful because we can essentially read cin into a string variable inputLine and any cin can be read from there. For each successive time we call the >> operator, we read a new piece of data into a variable. The reading cursor is the only thing that moves.

Other methods include:

  • str() converts a string stream to a string. If we called cout << ss.str(), it would output all the content that was written to it. What’s in ss remains there.
  • eof() evaluates whether there are any sub-strings within the stream for us to read.

Other considerations

When passing string streams as function inputs, we must pass by reference, not by value.

To flush out a string stream, we can use ss.str("").