Automating Type Conversions with stringstream Objects (cont'd)

Inserting a Value to a Stream
A stringstream-based conversion consists of two operations: writing the value to a stringstream and extracting it. The stringstream object automatically performs the low-level conversion of the source type to string when you insert a value to it. Likewise, when you extract a value from the stringstream and write it to the target variable, the opposite conversion takes place.

Note: Do not confuse <sstream> classes with the outdated and deprecated <strstream> family of char*-oriented stream classes, namely strstreambuf, istrstream, ostrstream, and strstream. Although both libraries offer the same functionality more or less, the newer <sstream> library is superior in many respects.

In the following example, we define a stringstream object and insert a variable of type double to it. We use the stringstream overloaded << and >> operators for insertion and extraction.


#include <sstream>
using namespace std;
int main()
{
 double d=123.45;
 stringstream s;
 s << d; // insert double into stream
}

Note that stringstream objects have a built-in memory manager that takes care of allocating memory as needed. This is a major advantage as it eliminates the drudgery of manual memory management, potential buffer overflows, and memory leaks. To extract the value stored in s to a string, use the >> operator:


string val;
s >> value;

Now val contains the string "123.45".

The opposite conversion, namely double to string, is just as simple:


string val="124.55";
stringstream s;
double d=0;
s << val; // insert string
s >> d; // d now equals 124.55




Back to the Beginning
 
Next: Templatizing stringstream-based Conversion

Introduction
Inserting a Value to a Stream
Templatizing stringstream-based Conversion

Return to Get Help with Windows C/C++ Page

Return to Main Get Help Page


 






Implementing an abstract operation as an ordinary function forces you to define multiple instances of that function, thereby incurring considerable maintenance and debugging overheads.



Use stringstream objects to perform easy, safe, automatic, and object-oriented type conversions.


Find Out More
Eskimo.com FAQs

• "Optimize Abstract Operations with Function Templates"

Tech Tip: Prefer Stringstream Objects to Strstream Objects

Tech Tip: Avoiding Buffer Overflows




TALK BACK
During its standardization process, C++ deprecated several of its libraries and introduced newer libraries that superseded them. Thus, <iostream> superseded <iostream.h>, <fstream> superseded <fstream.h> and so on. Do you still use the old libraries in your code? In your opinion, were these changes really necessary and were they worth the trouble?


Sponsored Links