C++

What Is C++ Stringstream, and How to Use It?

A string object instantiated from the string class is a list data structure. The list is a series of characters, and it is appreciated as such. The C++ string object has many methods. However, it lacks certain operations, which are best offered if it is seen as a stream. That is where stringstream comes in. Stringstream is a stream, which can be used to:

– Count the number of words in a string object

– Obtain individual word frequencies in a string object

– Convert a word in text form in the string object to a number, and vice-versa

Moving characters from the string object to the C++ program is inputting and represented by the stringstream object. Moving characters from the C++ program to the string object is outputting. Stringstream (i.e. sstream) uses the istringstream and ostringstream classes. An object instantiated from istringstream is responsible for inputting characters to a stringstream. An object instantiated from ostringstream is responsible for outputting characters from a stringstream to a string object.

This tutorial explains what sstream is and how to use it. The target string object is part of the C++ program.

In order to do input, output, or both, in one session, the C++ program should begin with:

#include <string>

#include <sstream>

#include <iostream>

Article Content

Creating a Stringstream Object

It is known that stringstream can be declared and applied at the same time in one statement. However, that is not the approach in this tutorial. In this tutorial, a stringstream object is instantiated from a class in one statement and used in another statement.

A stringstream can be instantiated for reading (inputting). A stringstream can be instantiated for writing (outputting). A stringstream can be instantiated for both reading and writing.

To create a stream object for reading, use:

    sstream strm (ios_base::in);

where strm is the stream object; and “in” of the ios_base class means for reading.

To create a stream object for writing, use:

    sstream strm (ios_base::out);

where strm is the stream object; and “out” of the ios_base class means for writing.

To create a stream object for reading or writing, use:

    sstream strm (ios_base::in | ios_base::out);

where “ios_base::in | ios_base::out”, is for reading or writing.

Input Stringstream Operation

Text to input to a stringstream from a string object can be done in two ways: using the insertion (<<) operator or using the str() member function of the sstream class. The following program illustrates this for both ways:

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm1(ios_base::in);

        strm1 << "We are the world!";

        string stri2 = "This is the earth!";

        stringstream strm2(ios_base::in);

        strm2 << stri2;

        stringstream strm3(ios_base::in);

        strm3.str("Mars is next.");

        string stri4 = "What about Jupiter?";

        stringstream strm4(ios_base::in);

        strm4.str(stri4);

        return 0;

}

The string object can be the literal or the identifier. Note that in the declaration of the sstream object, “stringstream” is used and not “sstream”, though both terms mean the same thing. The term sstream should be used in the include directive.

Output Stringstream Operation

A word is any string text that does not have any space (‘ ‘) within. Outputting from a stringstream means sending a string word from the sstream object to a string object. This needs the extraction operator (>>). The following program sends a word from a sstream object to a string object:

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm;

        strm << "love";

        string stri = "hate";

        strm >> stri;

        cout << stri << endl;

        return 0;

}

The output is:

    love

Any string value that the string object might have had is replaced. If the stringstream is declared above and without any argument, then it is for input or output.

If the string value of the stringstream object (buffer) has spaces, then only the first word will be sent. The sstream member function, str(), has to be used to send the whole string value, including the spaces. Str() can be used to convert a string literal into the sstream content. It can also be used to return all the content of the stream buffer, including the spaces, to the string object. The following program illustrates this:

    #include <string>

#include <sstream>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm;

        strm << "I love her, but he hates her.";

        string stri;

        stri = strm.str();

        cout << stri << endl;

        return 0;

}

The output is:

I love her, but he hates her.

Sending First Few Words Into Variables

In the string,

“I love her, but he hates her.”

If the first 5 words are to be represented by the variables, a, b, c, d, e, then these variables can be made to hold the words. The following code illustrates this:

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm;

        strm << "I love her, but he hates her.";

        string a, b, c, d, e;

        strm >> a >> b >> c >> d >> e;

        cout << a << ' ' << b << ' '  << c << ' '  << d << ' '  << e << endl;

        return 0;

}

The output is:

I love her, but he

A single character is a word. Note that the comma has been joined with “her”. If the comma had been separated from “her”, then it would have been considered as a separate word.

Counting Number of Words in String Literal

In the previous section, only the first 5 words were identified. In order to send all the words to different variables, the number of words has to be known. If the problem is just to know the number of words in the sstream buffer, then that can be done in a while-loop. It is by sending all the words to one variable, while counting the number of times the sending is done, and until the end of the stream (end-of-file) is reached. The following code illustrates this:

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm;

        strm << "I love her, but he hates her.";

        int counter = 0;

        string temp;

        while (!strm.eof()) {

                strm >> temp;

                counter += 1;

        }

        cout << counter << endl;

        return 0;

}

The output is 7. The full stop is attached to the second “her”. Note that the indicator for the end-of-file is the sstream member function, eof().

Individual Word Frequencies

In the string value,

"I love her, and he loves her sister, though he hates her brother."

The word, “her”, occurs 3 times, and the frequency of “her” is indicated to be 3. The word, “he”, appears 2 times, and the frequency of “he” is said to be 2. The rest of the words have a frequency of 1 each. The frequency of each word can be determined as follows:

Have all the words in a C++ map without repetition. Consider the following statement:

mp[temp]++;

where mp is a map object. The first time this statement is encountered in a while-loop, it fits in a new key/value pair, whose key is the string word of the variable temp and whose value is 1. The next time it is encountered in the same while-loop, with this particular key, no new key/value pair is added to the map. The value of this key/value pair is simply incremented.

So, the strategy is to have this statement in a while-loop and all the words in the ssstream buffer being read into a temporary variable. And, each value for each key/value pair in the map finally becomes the frequency of the key (word). The following program illustrates this:

#include <string>

#include <sstream>

#include <map>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm;

        strm << "I love her and he loves her sister, though he hates her brother.";

        string temp;

        map<string, int> mp;

        while (strm >> temp) {

                mp[temp]++ ;

        }

        for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++)

                cout << it->first << " => " << it->second << endl;

        return 0;

}

The output is:

I => 1

and => 1

brother. => 1

hates => 1

he => 2

her => 3

love => 1

loves => 1

sister, => 1

though => 1

String to Number and Vice-Versa

String to Number

To convert a string word to a number, just send the string word from the sstrream buffer to a variable declared as a number. To convert to an int, send the string word to an int variable. To convert to a float, send the string word to a float variable. The following program illustrates these:

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm;

        strm << " 30 ";

        int myInt;

        strm >> myInt;

        int intResult = myInt + 10;

        cout << intResult << endl;

        strm << " 2.5 ";

        float myfloat;

        strm >> myfloat;

        float fltResult = myfloat + 0.3;

        cout << fltResult << endl;

        return 0;

}

The output is:

40

2.8

Number to String

To convert a number to a string word, just send the number to the sstream buffer. Then, read out the stream buffer into a string object. To convert an int to a string, sent the integer to the sstream. To convert a float to a string, send the float to the sstream. The following program illustrates these:

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

 

int main()

{

        stringstream strm1;

        int myInt = 30;

        strm1 << myInt;

        string intStr;

        strm1 >> intStr;

        string intStrRes = intStr + " good";

        cout << intStrRes << endl;

        stringstream strm2;

        float myflt = 2.5;

        strm2 << myflt;

        string fltStr;

        strm2 >> fltStr;

        string fltStrRes = fltStr + " yes";

        cout << fltStrRes << endl;

        return 0;

}

The output is:

30 good

2.5 yes

Two stream objects have been used here for the different number types.

Note: the sstream buffer consists of characters only.

Conclusion

Stringstream means String Stream. It is also written as sstream. It is a stream. The target for this stream is a string object. The stream can use the insertion operator (<<) and the extraction operator (>>). The stream is very helpful for the following purposes: counting the number of words in a string object, obtaining individual word frequencies in a string object, and converting a word in text form in the string object to a number, and vice-versa.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.