Automating Type Conversions with stringstream Objects
By Danny Kalev, C++ Pro

Certain type conversions, such as long to double and signed to unsigned, are automatic in C. However, when you convert strings to numeric values and vice versa, you have to use explicit cast operations. Usually, you allocate a buffer that will store the result and call an appropriate conversion function such as atoi(), sprintf() or sscanf(). This approach has substantial drawbacks. First, if the target buffer is too small to contain the result of the conversion operation, the onerous buffer overflow bug will occur and result in undefined behavior. Second, the traditional <stdio.h> conversion functions are type-unsafe—one can easily use the wrong format flag, inadvertently omit an ampersand before a pointer argument, or add a redundant ampersand before a non-pointer argument. Finally, you have to use a different function or format flag for each pair of types, e.g., atoi() for converting an ASCII string to int, "%f" for ASCII to float conversion and so on.

The Standard Library defines a family of string-oriented streams in the header <sstream>. These include std::istringstram for input, std::ostringstream for output and std::stringstream for both input and input operations. C++ also defines wide-character versions of these stream classes, namely std::wistringstream, std::wostringstream and std::wstringstream. In the following sections I will show how to use stringstream objects to perform easy, safe, automatic, and object-oriented type conversions



Converting strings to numeric values and vice versa usually requires the use of explicit cast operations. The drawbacks are many: buffer overflow bugs, the operations are type-unsafe, and you have to use a different function or format flag for each pair of types.



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

  
Next: Inserting a Value to a Stream

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

Return to Get Help with C/C++ Page

Return to Main Get Help Page


 




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