Stuff you should know about In- and Output with Streams
Today’s post is about what you should know about Iostreams. In particular, I write about formatted and unformatted In- and Output.
Input and Output Functions
C++ has four predefined stream objects for the convenience of dealing with the keyboard and the monitor.
The stream objects can be used to write a program that reads from the command line and returns the sum.
// Iostreams.cpp #include <iostream> int main(){ std::cout << std::endl; std::cout << "Type in your numbers(Quit with an arbitrary character): " << std::endl; int sum{0}; int val; while ( std::cin >> val ) sum += val; std::cout << "Sum: " << sum << std::endl; std::cout << std::endl; }
The program uses the stream operators << and >> and the stream manipulator std::endl.
- The insert operator << pushes characters onto the output stream std::cout.
- The extract operator >> pulls the characters from the input stream std::cin.
- You can build chains of insert or extract operators because both operators return a reference to themselves.
std::endl is a stream manipulator because it puts a ‘\n’ character onto std::cout and flushes the output buffer.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
Here are the most frequently used stream manipulators.
Input
You can read in two ways from the input stream: Formatted with the extractor >> and unformatted with explicit methods.
Formatted Input
The extract operator >>
- is predefined for all built-in types and strings,
- can be implemented for user-defined data types,
- can be configured by format specifiers.
The following code snippet shows a straightforward way to read two int‘s.
#include <iostream> ... int a, b; std::cout << "Two natural numbers: " << std::endl; std::cin >> a >> b; // < 2000 11> std::cout << "a: " << a << " b: " << b;
std::cin ignores by default leading whitespace.
Unformatted Input
An input stream supports a few methods for unformatted input.
- std::string has a getline function
The getline function of std::string has a big advantage over the getline function of the istream. The std::string automatically takes care of its memory. On the contrary, you have to reserve the memory for the buffer buf in the call is.get(buf, num). Using the getline function is quite convenient because you can also specify a delimiter:
// inputUnformatted.cpp #include <fstream> #include <iostream> #include <string> int main(){ std::cout << std::endl; std::string line; std::cout << "Write a line: " << std::endl; std::getline(std::cin, line); // (1) std::cout << line << std::endl; std::cout << std::endl; std::ifstream inputFile("test.txt"); while ( std::getline(inputFile, line, ';') ) { // (2) std::cout << line << std::endl; } }
First, the program reads in line (1) for std::cin; second, it reads in line (2) from the file test.txt.
For simplicity reasons, the code does no error handling. You can read the error handling details in my last post: C++ Core Guidelines: iostreams. The file test.txt contains numbers, which are separated by “;”.
Output
As promised in my last post C++ Core Guidelines: iostreams, here are the format specifiers for iostreams; you should know, or at least know, where to find them.
Important Format Specifiers
I often hear students who are experienced C++ programmers in my classes complain that arithmetic in C++ is not precise enough. The reason is mostly not C++ but the default format specifiers for the Iostreams. Let’s see what you should know:
First of all. You can use manipulators or flags that specify the format.
Manipulators and Flags
// formatSpecifier.cpp #include <iostream> int main(){ std::cout << std::endl; int num{2011}; std::cout << "num: " << num << "\n\n"; std::cout.setf(std::ios::hex, std::ios::basefield); // (1) std::cout << "hex: " << num << std::endl; std::cout.setf(std::ios::dec, std::ios::basefield); // (1) std::cout << "dec: " << num << std::endl; std::cout << std::endl; std::cout << std::hex << "hex: " << num << std::endl; // (2) std::cout << std::dec << "dec: " << num << std::endl; // (2) std::cout << std::endl; }
Lines (1) use flags and lines (2) manipulators to format the output.
From the readability and maintainability point of view, I strongly prefer manipulators.
Manipulators for the Iostreams
Okay, let me start with the essential manipulators.
The following tables present the relevant format specifiers. The format specifiers are sticky except for the field width, which is reset after each application.
The manipulators without arguments need the header <iostream>, and those with arguments need the header <iomanip>.
- Boolean Values
- Field With and Fill Characters
- Alignment of Text
- Positive Signs and Upper/Lower Case
- Numeric Base
- Floating Point Numbers
There are special rules for floating-point numbers:
- The number of significant digits (digits after the comma) is, by default, 6.
- If the number of significant digits is not big enough, the number is displayed in scientific notation.
- Leading and trailing zeros are not displayed.
- If possible, the decimal point is not displayed.
After so much theory, here are the format specifiers in action.
// formatSpecifierOutput.cpp #include <iomanip> #include <iostream> int main(){ std::cout << std::endl; std::cout << "std::setw, std::setfill and std::left, right and internal: " << std::endl; std::cout.fill('#'); std::cout << -12345 << std::endl; std::cout << std::setw(10) << -12345 << std::endl; std::cout << std::setw(10) << std::left << -12345 << std::endl; std::cout << std::setw(10) << std::right << -12345 << std::endl; std::cout << std::setw(10) << std::internal << -12345 << std::endl; std::cout << std::endl; std::cout << "std::showpos:" << std::endl; std::cout << 2011 << std::endl; std::cout << std::showpos << 2011 << std::endl; std::cout << std::noshowpos << std::endl; std::cout << "std::uppercase: " << std::endl; std::cout << 12345678.9 << std::endl; std::cout << std::uppercase << 12345678.9 << std::endl; std::cout << std::nouppercase << std::endl; std::cout << "std::showbase and std::oct, dec and hex: " << std::endl; std::cout << 2011 << std::endl; std::cout << std::oct << 2011 << std::endl; std::cout << std::hex << 2011 << std::endl; std::cout << std::endl; std::cout << std::showbase; std::cout << std::dec << 2011 << std::endl; std::cout << std::oct << 2011 << std::endl; std::cout << std::hex << 2011 << std::endl; std::cout << std::dec << std::endl; std::cout << "std::setprecision, std::fixed and std::scientific: " << std::endl; std::cout << 123.456789 << std::endl; std::cout << std::fixed << std::endl; std::cout << std::setprecision(3) << 123.456789 << std::endl; std::cout << std::setprecision(4) << 123.456789 << std::endl; std::cout << std::setprecision(5) << 123.456789 << std::endl; std::cout << std::setprecision(6) << 123.456789 << std::endl; std::cout << std::setprecision(7) << 123.456789 << std::endl; std::cout << std::setprecision(8) << 123.456789 << std::endl; std::cout << std::setprecision(9) << 123.456789 << std::endl; std::cout << std::endl; std::cout << std::setprecision(6) << 123.456789 << std::endl; std::cout << std::scientific << std::endl; std::cout << std::setprecision(6) << 123.456789 << std::endl; std::cout << std::setprecision(3) << 123.456789 << std::endl; std::cout << std::setprecision(4) << 123.456789 << std::endl; std::cout << std::setprecision(5) << 123.456789 << std::endl; std::cout << std::setprecision(6) << 123.456789 << std::endl; std::cout << std::setprecision(7) << 123.456789 << std::endl; std::cout << std::setprecision(8) << 123.456789 << std::endl; std::cout << std::setprecision(9) << 123.456789 << std::endl; std::cout << std::endl; }
The output should be sufficient to explain the program formatSpecifierOutput.cpp.
What’s next?
When you synchronize too much, you lose. In the case of the Iostreams, you will lose performance. I will show you the numbers in my next post.
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, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, 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, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.
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 | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!