Computer Science 1704
Intro to Data Structures & Soft Eng

String Streams


C++ stream I/O provides classes for performing I/O to/from strings, termed string stream processing. The string stream class names are istringstream and ostringstream and are defined in the header <sstream>. (Programs using <sstream> must also include <iostream>.) All of the functionality provided by streams can be applied to string streams.

Initialization & Assignment

String streams are initialized upon definition by passing a string constant or string object to the constructor function. Output stringstreams can be assigned data by using the insertion operator. of which multiple uses of << results in concatenation.


#include <iostream> 
#include <sstream>
#include <string>
using namespace std;

void main(void) {

string twob ("2B || !2B i.e. the ? ");

istringstream istr(twob);
ostringstream ostr;
ostr << twob << twob;

cout << "istr = " << istr.str() << endl;
cout << "ostr = " << ostr.str() << endl;


Stringstream objects use an internal string sub-object to store their data. The stringstream member function str() returns a string reference to the internal string sub-object. The above example would output:

istr = 2B || !2B i.e. the ?

ostr = 2B || !2B i.e. the ? 2B || !2B i.e. the ?


Input from an initialized input stringstream may be preformed by using the extraction operator. This allows for easy conversions between strings and other types by using the automatic text conversions built into streams.

#include <iostream> 
#include <sstream>
#include <string>
using namespace std;

float stof (string strf);

void main(void) {

string pi ("PI = 3.14159");
float pif = 0.0f;

pif = stof( pi.substr(5,7) );
cout << "pif = " << pif << endl;


float stof (string strf) {

istringstream istr(strf);
float tmpf;

istr >> tmpf;
return(tmpf) ;



The above example would output:

pif = 3.14159



D. Barnette 1/20/2000 Virginia Tech © 1995-2000