Stuff you should know about In- and Output with Streams

Contents[Show]

Today's post is about what you should know about Iostreams. In particular, I write about formatted and unformatted In- and Output.

 

temple 1717088 1280

Input and Output Functions

C++ has four predefined stream objects for the convenient dealing with the keyboard and the monitor.

PredefinedStreamObject

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;

}

 

Iostreams

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.

Here are the most frequently used stream manipulators.

StreamManipulators Input

You can read in two way 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.

UnformattedInput

  • std::string has a getline function

The getline function of std::string has a big advantage to 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 details to error handling in my last post:  C++ Core Guidelines: iostreams. The file test.txt contains numbers, which are separated by ";"

 inputUnformatted

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 here students, which are experienced C++ programmers, in my classes complain that arithmetic in C++ is not precise enough. The reason is most of the times not C++ but the default format specifiers for the Iostreams. Let see what you should know:

First of all. You can use manipulators or flags the 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;

}

 

The lines (1) use flags and the lines (2) manipulators to format the output.

formatSpecifier

From the readability and maintainability point of view, I strongly prefer manipulators.

Manipulators for the Iostreams

Okay, let me start with the most essential manipulators.

The followings 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 any arguments need the header <iostream>, and the manipulators with arguments need the header <iomanip>.

  • Boolean Values

BooleanValue

  • Field With and Fill Characters

FieldWithAndFillCharacters

  • Alignment of Text

Alignment

  • Positive Signs and Upper/Lower Case

FloatingPointNumbers

  • Numeric Base

NumericBase

  • Floating Point Numbers

FloatingPointNumbers

 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 be displayed.
  • If possible, the decimal point is not be 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.

formatSpecifierOutput

What's next?

When you synchronise too much, you lose. In the case of the Iostreams, you will lose performance. I show you the numbers in my next post.

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Wolfgang Gärtner,  Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Avi Kohn, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, and Tornike Porchxidze.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, and Richard Sargeant.

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

Seminars

I'm happy to give online-seminars or face-to-face seminars world-wide. Please call me if you have any questions.

Bookable (Online)

Deutsch

English

Standard Seminars 

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmSmall

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 6465

Yesterday 7909

Week 14374

Month 89425

All 6110489

Currently are 139 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments