C++ Programming/Code/Standard C Library/Functions/scanf

From Wikibooks, open books for an open world
Jump to: navigation, search

scanf[edit]

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 Character Explanation
 %c a single character
 %d a decimal integer
 %i an integer
 %e, %f, %g a floating-point number
 %lf a double
 %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.

This 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 %f\n", i, f, d );
Related topics
fgets - fscanf - printf - sscanf