Using Stringstreams in C++
(Page 1 of 4 )
Variety is the spice of life; if you could see the same things each day, drink the same coffee, meet the same people, eat the same things, life would be absolutely boring. The drawback of this, on the other hand, is that coordinating such variety can be a big challenge. Copied from the multiplicity in our world, we have a significant diversity of types within the C++ programming world. This is not always a good thing. This article will explain how to tackle this challenge with help from streams and the STL class.
Many beginner coders, in fact, struggle with the conversions from one type to another. Probably the most troublesome problem turns out to be adding numbers of type integer and float to the std class string.
If you've always cursed this process, I invite you to continue reading this article. Even if you haven't, sit back, relax, and observe a solution that is simpler to write and maintain than the ones you may have used inside C (itoa, atoi, and others) until now.
This article is the ninth part of a series about streams in C++. Therefore, if you lack some general knowledge about this or the STL class string, I strongly encourage you to search for and read one or more of my articles about this published here on the Developer Shed Network under the names: Introduction to Streams, Basic IO in C++ or The String STL Class.
Today we will see how we can combine the power of the stream and the advantages of the STL class string together to make conversion of objects inside the C++ a seamless and trivial task.
As you may already recognize the benefits of streams as an easy way to read and write data with just the use of the insertion and extraction operator (<< and >>), the profit from strings is obvious: they offer an array of chars that does not need buffer management.
Working with streams to handle files has proven to be an efficient and comprehensible approach for all new programmers. You could read in any value with just the extraction operator and print anything, and in the background, the stream took care of the type of the input/output.
This is a safer and faster method than the old one existing inside the scanf, as you could no longer cause inconsistency issues between the values you passed as an argument for printing and what you specified to be inside the formatting string. For that reason, the question came up as to why you should create a new file to benefit from this.
A stream created inside the memory poll could assure that you can use all of that with some improved performance as compared to a proper file on the disk. The result of this is now known inside the C++ language as the stringstream class.
Next: Using It for Input >>
More C++ Articles
More By Gabor Bernat