C scanf()

The scanf() function is a general-purpose input routine that reads the stream stdin and stores information in the variables pointed to in its arguments list. It can read all the built-in data types and automatically converts them into the proper internal format.

The control string pointed to by format consists of the following three classifications of characters :

  • Format Specifiers
  • White-space characters
  • Now-white-space characters

Following table lists the scanf() format specifiers :

C Programming Table:
Code Meaning
%a Read a floating-point value
%A Same as %a
%c Read a single character
%d Read a decimal integer
%i Read an integer in either decimal, octal or hexadecimal format
%e Read a floating-point number
%E Same as %e
%f Read a floating-point number
%F Same as %f
%g Read a floating-point number
%G Same as %g
%o Read an octal number
%s Read a string
%x Read a hexadecimal number
%X Same as %x
%P Read a pointer
%n Receive an integer value equal to the number of characters read so far
%u Read an unsigned decimal integer
%[] Scan for a set of characters
%% Read a percent sign

scanf() Syntax

int scanf(const char *format, ...);

scanf() Example

Following c program uses the scanf() function. The operation of these scanf() statements is explained in their comments :

void main()
	char str1[80], str2[80];
	int i;
	/* read a string and an integer */
	scanf("%s%d", str1, &i);
	/* read up to 79 characters into str1 */
	scanf("%79s", str1);
	/* skip the integer between the two strings */
	scanf("%s%*d%s", str1, str2);

C Online Test

« Previous Function Next Function »