Back to DFS's C Page


Input/Output II

scanf()

Input and output routines are provided in the C language. To access the functions for using formatted input and output, the following compiler control line must be included at the beginning of the source file:

#include <stdio.h>

This include file is in /usr/include and contains the header information for STandarD Input/Output functions. This documentation only explains the basics; check the man pages for further information.

scanf() reads input from standard input, the keyboard being the default. Its syntax is as follows:

numconvert = scanf(control_string, ptr1, ptr2, ...)

The format control string is a double-quoted text string which contains conversion and formatting information about how the remaining arguments are to be handled. For each conversion specified in the control string, a pointer to a variable is given. numconvert will receive the return value from scanf as an integer indicating how many conversions have been successfully completed. Given the following declarations, an example prompt and call could take the form below:

int h; /* height */
int success; /* flag for successful conversion */

printf("What is the triangle's height? ");
success = scanf("%d", &h);

and would accept a decimal integer as input, convert it to binary, and store the value in variable h. The return value does not need to be utilized.

White space (word spaces, tabs, newlines) are ignored. Bad input, such as an alphabetic character, will result in no conversion being performed and later scanf calls will fail due to the newline character which remains in the input buffer. To avoid bad input, see Functions III.

The Formatting Information

Between the % and the conversion character (d in the case above), it is possible to include various formatting information, in the following order. All of these are optional.

* Discard the conversion that follows.
nn A numeric value to specify the maximum field width.
l
L
Requires a long int for dioux or double for f;
requires a long long for dioux or long double for f.

The Conversion Characters

d Read the input as a possibly signed decimal integer.
u Read the input as an unsigned decimal integer.
i Read the input as a possibly signed decimal, octal, or hexadecimal integer.
o Read the input as an unsigned octal integer.
x Read the input as an unsigned hexadecimal integer.
c Read the input as a character.
s Read the input as is a string; a null character is appended.
f Read the input as a floating-point.

Some Examples

char a; char b[10];
scanf("%c%s", &a, b);
INPUT: Hello
RAM: a = 'H'
     b = "ello"

int d, m, y;
scanf("%d-%d-%d", &d, &m, &y);
INPUT: 5-4-48
RAM: d = 5
     m = 4
     y = 48

int d, m, y;
scanf("%d%*c%d%*c%d", &d, &m, &y);
INPUT: 5/4/48
RAM: d = 5
     m = 4
     y = 48


© DFStermole: 14 Oct 1998
HTMLified 14 Oct 1998