scanf

C++ Reference

scanf
Syntax:
  #include <stdio.h>
  int scanf( const char *format, ... );

The scanf() function reads input from STDIN, according to the given format, and stores the data in the other arguments. It works a lot like printf(). The format string consists of control characters, whitespace characters, and non-whitespace characters. The control characters are preceded by a % sign, and are as follows:

Control Character Explanation
%c a single character
%d a decimal integer
%i an integer
%e, %f, %g a floating-point number
%o an octal number
%s a string
%x a hexadecimal number
%p a pointer
%n an integer equal to the number of characters read so far
%u an unsigned integer
%[] a set of characters
%% a percent sign

scanf() reads the input, matching the characters from format. When a control character is read, it puts the value in the next variable. Whitespace (tabs, spaces, etc) are skipped. Non-whitespace characters are matched to the input, then discarded. If a number comes between the % sign and the control character, then only that many characters will be converted into the variable. If scanf() encounters a set of characters, denoted by the %[] control character, then any characters found within the brackets are read into the variable. The return value of scanf() is the number of variables that were successfully assigned values, or EOF if there is an error.

Example code:

This code snippet repeatedly uses scanf() to read integers and floats from the user. Note that the variable arguments to scanf() are passed in by reference, as denoted by the ampersand (&) preceding each variable:

 int i;
 float f;               

 while( 1 ) {
   printf( "Enter an integer: " );
   scanf( "%d", &i );             

   printf( "Enter a float: " );
   scanf( "%f", &f );             

   printf( "You entered %d and then %f\n", i, f );
 }              
Related topics: