String Stream Constructors [C++ Reference]
Keywords: io,sstream,constructors
Date: 2009-10-10T20:48:45-0700

[[String Stream Constructors]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## String Stream Constructors

Syntax:

        #include <sstream>
        stringstream();
        explicit stringstream( ios_base::openmode mode );
        stringstream( const string& s, ios_base::openmode mode );
        ostringstream();
        explicit ostringstream( ios_base::openmode mode );
        ostringstream( const string& s, ios_base::openmode mode );
        istringstream();
        explicit istringstream( ios_base::openmode mode );
        istringstream( const string& s, ios_base::openmode mode );

The stringstream, ostringstream, and istringstream objects are used for input and output to a string. They behave in a manner similar to fstream, ofstream and ifstream objects.

The optional `mode` parameter defines how the file is to be opened, according to the IO stream mode flags.

An ostringstream object can be used to write to a string. This is similar to the Standard C Library sprintf function. For example:

        ostringstream s1;
        int i = 22;
        s1 << "Hello " << i << endl;
        string s2 = s1.str();
        cout << s2;

An istringstream object can be used to read from a string. This is similar to the Standard C Library sscanf function. For example:

        istringstream stream1;
        string string1 = "25";
        stream1.str(string1);
        int i;
        stream1 >> i;
        cout << i << endl;  // displays 25

You can also specify the input string in the istringstream constructor as in this example:

        string string1 = "25";
        istringstream stream1(string1);
        int i;
        stream1 >> i;
        cout << i << endl;  // displays 25

A stringstream object can be used for both input and output to a string like an fstream object.

Related Topics: C++ I/O streams

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •