scanf

Syntax:

    #include <cstdio>
    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 CharacterExplanation
%ca single character
%da decimal integer
%ian integer
%e, %f, %ga floating-point number
%lfa double
%oan octal number
%sa string
%xa hexadecimal number
%pa pointer
%nan integer equal to the number of characters read so far
%uan 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.

Use Control Character Explanation '*' to ignore variables. Example:

  int i;
  scanf("%*d %d",&i);
  printf("%d",i);

Input:3 4 Output:4

The following code snippet uses scanf() to read an int, float, and a double from the user. Note that the variable arguments to scanf() are passed in by address, as denoted by the ampersand (&) preceding each variable:

   int i;
   float f;
   double d;
 
   printf( "Enter an integer: " );
   scanf( "%d", &i );
 
   printf( "Enter a float: " );
   scanf( "%f", &f );
 
   printf( "Enter a double: " );
   scanf( "%lf", &d );
 
   printf( "You entered %d, %f, and %lf\n", i, f, d );

Related Topics: fgets, fscanf, printf, sscanf