5.9.2.3. Stdio: Reading from the Standard Input

To use the things described here, #include the <cstdio> library.

scanf(format, ...)

Use scanf to read from the standard input. The format describes the kinds of things to be read. After that is a list of memory addresses of variables where the results should be put. For example, statement
  scanf("%i%i", &x, &y);
reads two integers (type int, indicated by %i). It stores the first one into x and the second one into y. Reading formats include
  • %li (read a long integer);
  • %f (read a value of type float);
  • %lf (read a value of type double);
  • and %c (read a single character and put it into a variable of type char);
  • a space in a format indicates that an arbitrary amount of white space (spaces, tabs, end-of-line characters) should be skipped.
For example,
  char c;
  scanf(" %c", &c);
reads the next non-white-space character in the standard input and stores it into variable c.

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

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


getchar()

This expression reads one character from the standard input and returns it. The result has type int, not type char. The result is normally the nonnegative integer code of the character that was read. But if there are no more characters to read, getchar returns EOF, which is −1. You would typically see
  int c;
  c = getchar();
  if(c != EOF)
  {
     (do something with c)
  }

eof()

Expression eof() is true if an attempt to read the standard input has been done, and the standard input was found to have nothing left in it.

I do not recommend that you use eof. It does not ask whether there is anything left in the standard input. It only returns true if you have already tried to read past the end of the file.

If you are typing on a Linux terminal, type a control-D to simulate an end of file.