# is replaced by any whole number (e.g. 5)
* Discussed in a Later Lesson.
The placeholder specifies the maximum number of characters to be used in
the input conversion (field width).
inp = fopen("circle.dat", "r");
e.g. fscanf (inp, "%41f", &radius);
When a program has no further use for its input and output files, it
closes them by calling fclose.
The double variable radius is to be input from the file represented by
inp, reading a maximum of 6 columns into the variable radius.
The integer variable item and the double variable value are input from
columns 1-4 and 5-14, respectively, assuming no white space separates
the digits.
Computers interpretations:
e.g.:
TOPICS
Credits for Lecture and
Authoring
Formatted Input
Format for scanf
Variables and scanf
Placeholder
Examples
File Usage
Stdio.h
Scan Format Examples
Character I/O
Sample Program
Program Output
CREDITS FOR LECTURE AND AUTHORING
Authored by: John Even
Faculty Supervisor: Al Day
Some material is derived from a lesson by: Dr. James Hilliard
HTML Documentaion by: Michelle Roberts
Last Updated: 7/24/96
FORMATTED INPUT![]()
scanf("%cs1%cs2", &var1, &var2);
FORMAT FOR scanf![]()
or
fscanf(fp, "%cs1%cs2", &var1, &var2);
FORMAT FOR DIFFERENT VARIABLE TYPES
![]()

# is completely optional and may be omitted for
default input.
The number is the Placeholder.
HOW TO USE #'S FOR FORMATTED INPUT:![]()
When scanning a number into a variable,
white spaces preceding the number are ignored. White space includes the
space character, the tab character and the newline character (\n).
EXAMPLES![]()
b represents a blank space
* The unused portion of the input line will be saved for later input.
To use a file, three things must be done.
FILE USAGE![]()
Declaring a Pointer
*outp; /* pointer to output file */
Opening the File
outp = fopen("cirlce.out", "w");
fclose
e.g. fclose(inp);
fclose(outp);
In the header file stdio.h, there are also some preset FILE*
pointers. These are stdin, stdout, and stderr. Unlike other
FILE* pointers, these will send I/O to the keyboard or monitor
depending on the type.
stdio.h![]()
stdin --- keyboard
Using these predeclared pointers, fprintf and fscanf can be used in
place of printf and scanf in all cases.
stdout --- monitor
stderr --- monitor
fscanf(inp, "%61f", &radius);
SCAN/FORMAT EXAMPLES![]()
Example 2
More Examples
- A double number is input from the current data line.
- The field for this number is up to the first 8 columns of the line, not
counting white space.
Variables of type char can be scanned and printed in the same fashion as
variables of types int and double.
CHARACTER INPUT/OUTPUT![]()
scanf("%c", &var);
% c : conversion specification for character type I/O
printf("The initial is %c", var);
var : character variable