Introduction to Streams - How Should They Look?
(Page 3 of 4 )
This segment answers both where and why to use the streams and what conventions should be followed. First of all, the designer of streams himself said that “An I/O facility should be easy, convenient, and safe to use; efficient and flexible; and above all, complete”—Bjarne Stroustrup. The easy part is matched by the conventions: the operator >> stands for inputting something into a stream and the operator << assures the extraction from a stream.
As long as you use this to accomplish the insertion and extraction, you shouldn’t have any problems. C++ is safe, efficient and flexible in its internal design. Even if you consider the performance factor, the C++ iostream library should be preferred above the C stdio library.
I'd also like to mention the printf and scanf functions. These aren’t safe, as the type conversion isn't secure (you can give an invalid parameter list), and besides, you have to parse the parameter itself. This on its own adds a little performance penalty. In C++ this can be avoided by using overloaded operators and functions.
One of the most important features of streams is their extensibility. This means you can extend the compatibility of the stream to work with your own newly- created classes/types. This should be self explanatory if you understand OOP programming under C++; how to make this happen will be covered in a future article of these series.
Internationalization is also on the agenda, as streams should support all character types, so everyone can use them regardless of where and under which language support the program was written. This is related to the support of the UNICODE character system.
Indeed nowadays every application tries to reach a larger market segment by offering support for most of the languages (Chinese, Russian or English – it doesn’t matter). Most of the time it is a good idea to work under the UTF16 character set inside your application even if the output will be under the UTF8 set (ASCI).
One other criterion should be taken into account: flexibility. This means that the streams shouldn’t necessarily be connected to the I/O connections of the operating system. For instance, why shouldn’t we have a stream on the hard drive (as a file) but also temporarily in memory?
Happily, during the evolution of the library, all of this has been achieved and integrated into the STL library. I’ve written an article series about this here on the Developer Shed Network, so feel free to grasp that knowledge also if you like. Meaning… stay tuned!
Portability is also a good reason for using streams, along with the fact that they give an elegant look to your code snippet by inspiring transparency and clarity.
Next: Conclusion >>
More C++ Articles
More By Gabor Bernat