6A. Input and Output


Textual input and output

A program needs some way of communicating with the user. The two most common ways to do that are:

Graphical input and output is important, but it is a big topic, and is not the focus of this course. We will restrict ourselves to textual input and output. A program reads information that the user types on the keyboard, and writes or prints information into a terminal window. (The terms write and print are generally used interchangeably when discussing textual output.)


Standard input and standard output

Standard output

A program writes on the terminal by writing to the standard output. For brevity, I will refer to the standard output as stdout.

By default, stdout is the terminal. But you can redirect it so that anything written to stdout goes into a file instead.

Output redirection is a feature of Linux (and other operating systems, including Windows), not of C++. To redirect stdout to file F, write >F after a Linux command. For example,

  jump up >jump-out.txt
runs command
  jump up
with the standard output going to file jump-out.txt.


Standard input

To read from the keyboard, use the standard input. For brevity, I will refer to the standard input as stdin.

By default, stdin is the keyboard, but you can redirect stdin so that it comes from a file. To make stdin come from file F, add <file to the end of a Linux command. For example,

  jump up <data.txt
runs command
      jump up
but arranges for its standard input to come from file data.txt. That is very useful for testing. If you just put a test input in a file, then you don't need to type it again each time you modify your program.

If you do not redirect stdin and, as you type the input, you want to simulate an end-of-file, type Control-D.


Redirecting both stdin and stdout

To redirect both stdin and stdout, put both redirections at the end of a command, in either order. For example,

  ./foo <data.txt >jump-out.txt
runs command
  ./foo
with stdin coming from file data.txt and stdout going to file jump-out.txt.



Summary

Typically, a program reads from the standard input and writes to the standard output.

By default, the standard input is tied to the keyboard and the standard output is tied to the terminal window. But you can redirect them to files.


Exercises

  1. What is the difference between the standard input and the keyboard? Answer

  2. Write a Linux command that runs executable program hailstone with its standard input coming from file h-in.txt and its standard output going to file h-out.txt. Answer