6C. Reading


Scanf

The <cstdio> library also provides a function, scanf, for reading information from stdin. The <cstdio> library is a library for C. C++ programs can use it, but to fully understand what is going on, we need to talk about memory addresses.

Using scanf

The first parameter of scanf is a format string describing the things to be read. After that is a list of memory addresses of variables where the values that are read should be put. The memory address of variable z is written &z. For example, statement

  scanf("%i%i", &x, &y);
reads two integers and stores them into variables x and y, which must have type int. The first value goes into x and the second one into y. Formats for reading include

  • %d or %i (read an int)

  • %li (read a long integer);

  • %lf (read a value of type double);

  • a space in an input format indicates that an arbitrary amount of white space (spaces, tabs, end-of-line characters) should be skipped. White space is skipped anyway before reading a number. Some formats that we see later do not automatically skip white space.


What if the read cannot be done?

Sometimes a read cannot be accomplished. For example, if you ask to read an integer, but the program sees abc, then it cannot read the integer. Scanf stops reading at the first failure and returns the number of items successfully read. So

  int status = scanf("%i%i", &x, &y);
  if(status < 2)
  {
    what to do if it was not possible to read both x and y
  }
is a typical way to use scanf.

If scanf encounters the end of a file without reading any of the items sought, it returns EOF, which is a name for −1. To test for EOF, write EOF, not −1. That way, a reader understands what you are doing. For example,

  if(status == EOF)
  {
    ...
  }


Prompts

When a program reads information from the standard input, it usually writes something to let the user know to type the required information. For example,
  printf("What number should I use? ");
  scanf("%i", &num);
But do not overdo it. If the input is supposed to have a particular rigid form, don't write a prompt for each line. It is annoying.

getchar

Function getchar reads a character from the standard input and returns that character. But if there are no more characters available, it returns EOF. Because getchar can return EOF, which is not a character, its result has type int, not char.

To illustrate, the following function reads the entire standard input and writes it verbatim to the standard output. It uses a while-loop, covered later.

  void echoStdin()
  {
    int c;
  
    c = getchar();
    while(c != EOF)
    {
      putchar(c);
      c = getchar();
    }
  }


Standards

See the following standards for input.


Exercises

  1. Write a definition of function readInt() that reads one integer from the standard input and returns that integer. Assume that the read is successful. Answer