Stringstream classes in C++

The use of stringstream classes in C++ is similar with #include cin and cout components of a C++ program. The string stream is just another object, just like cout but the data goes into a C++ string instead to the console.

To be able to implement stringstreams, the #include header file is required. The advantage of using string streams is that it can be convenient to between strings and other numerical types.

The basic methods for stringstream include

  • clear() – Clears the error bits in the stringstream object so that it can be used again. It must be called each time you start parsing a new string with the stringstream object.
  • str() – Returns the string associated with the stringstream object
  • str(s) – Associates the string s to the stringstream object
  • operator << – Add a string to the stringstream object
  • operator >> – Read something from the stringstream object

In the example code below is applying stringstream to convert strings and other numerical types.

<pre>#include <iostream>
#include <sstream>

using namespace std;

int main() { // create string object holding a number
string str = "15.40 1540 hello world";
stringstream ss; // create a stringstream object

ss << str; // feed in the value held in the string object
float myFloat = 0;
int myInt = 0;
char myArray[20] = {};
char myChar = 0;

ss >> myFloat;
ss >> myInt;
ss >> myArray;
ss >> myChar;

cout << "myFloat =" << myFloat << endl;
cout << "myInt =" << myInt << endl;
cout << "myArray =" << myArray << endl;
cout << "myChar =" << myChar << endl;

Share this post