When you interact with the outside world, the iostream library is the way to go in C++. As always, you have to keep a few rules in mind. Let me show which rules.
The C++ core guidelines give a good overview of iostreams:
"iostreams is a type safe, extensible, formatted and unformatted I/O library for streaming I/O. It supports multiple (and user extensible) buffering strategies and multiple locales. It can be used for conventional I/O, reading and writing to memory (string streams), and user-defines extensions, such as streaming across networks (asio: not yet standardized).“
Surprisingly for me, and in contrast to the fact, that iostreams are quite essential and are used by most C++ developers, there are only five rules which deal with them, and these rules do have not much content. Here are they:
- SL.io.1: Use character-level input only when you have to
- SL.io.2: When reading, always consider ill-formed input
- SL.io.3: Prefer iostreams for I/O
- SL.io.10: Unless you use
printf-family functions call
- SL.io.50: Avoid
I have to add additional information to make a story out of the rules. This is not necessary for the first rule:
First, here is a bad example from the guidelines. Using character-level input for more than one character:
This is a terrible solution for a simple job. My remark does not hold for the right way to do it:
Presumably, the better way is also the faster way.
The following rule states a no-brainer.
The question is now: How can we deal with bad data? Each stream has a state associated.
State of the Stream
Flags represent the state of the stream. The methods for dealing with these flags need the header <iostream>.
Examples causing the different states of a stream
- Reading beyond the last valid character.
- False formatted reading.
- Reading beyond the last valid character.
- Opening of a file went wrong.
- Size of the stream buffer cannot be adjusted.
- Code conversion of the stream buffer went wrong.
- A part of the stream threw an exception.
stream.fail() returns whether std::ios::failbit or std::ios::badbit is set.
Reading and setting the state of a stream
- Initializes the flags and sets the stream in the goodbit state
- Initializes the flags and set the stream into the state sta.
- Returns the current state.
- Sets the additional flag fla.
Operations on a stream have only an effect if the stream is in the goodbit state. If the stream is in the badbit state, it can not be reset to the goodbit state.
The input of the string wrongInput causes the stream std::cin to be in std::ios::failbit state. Consequently, wrongInput and std::cin.fail() cannot be displayed. First, you have to set the stream std::cin in the goodbit state.
You can show your output with printf or with iostreams. My tip is obvious.
The following two program displays two times the equivalent formatted data. First, by using
printf and format strings; second, by using iostreams and format manipulators.
As promised, the same output:
Okay, but why should you prefer iostreams to printf? There is a subtle but critical difference between printf and iostreams. The format string with printf specifies the type, and the format of the displayed value, and the format manipulator with iostreams specifies only the format. To say it the other way around: The compiler deduces the correct type automatically in case of an isotream.
Let me make my point clear. You get undefined behavior when you have a bad day or are new to C++ and specify the wrong type in a format string.
This is what undefined behavior looks like on my local PC.
Of course, the compiler usually writes a warning in case of a wrong format string, but you have no guarantee. Additionally, I know what often happens when the deadline is passed. You ignore the warnings and, maybe, will look at it later. Instead of dealing with errors, don’t make errors in the first place.
The difference between printf and iostreams reminds me of the most important design guideline from Scott Meyers: “Make interfaces easy to use correctly and hard to use incorrectly.“
I used in the iostream example format specifiers. To simplify your life as a software developer, you should keep a few format manipulators in mind. Let me show in my next post, which ones.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, and Bhavith C Achar.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,