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: Paul Baxter,  Meeting C++, Matt Braun, Avi Lachmish, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Marko, Ramesh Jangama, G Prvulovic, Reiner Eiteljörge, Benjamin Huth, Reinhold Dröge, Timo, Abernitzke, Richard Ohnemus , Frank Grimm, Sakib, and Broeserl.

Thanks in particular to:  TakeUpCode 450 60     crp4

 

Get your e-book at Leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 600 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

Get your interactive course

 

Modern C++ Concurrency in Practice

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

educative CLibrary

Based on my book "Concurrency with Modern C++" educative.io created an interactive course.

What's Inside?

  • 140 lessons
  • 110 code playgrounds => Runs in the browser
  • 78 code snippets
  • 55 illustrations

Based on my book "The C++ Standard Library" educative.io created an interactive course.

What's Inside?

  • 149 lessons
  • 111 code playgrounds => Runs in the browser
  • 164 code snippets
  • 25 illustrations

Add comment


Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 389

All 2293483

Currently are 109 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments