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).

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.

eof()

Expression eof() is true if the standard input has no more characters in it. This is often used when the standard input has been redirected to a file. If you are typing on a Linux terminal, type a control-D to simulate an end of file.