scanf
Scans and formats input from the stdin stream.
Defined in header <stdio.h>
Syntax
#include <stdio.h>
int scanf(const char *format[, address,...]);
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ |
Remarks
scant scans a series of input fields, one character at a time, reading from the stdin stream. Then each field is formatted according to a format specifier passed to scant in the format string pointed to by format. Finally, scant stores the formatted input at an address passed to it as an argument following/ormflf. There must be the same number of format specifiers and addresses as there are input fields.
The format string
The format string present in scant and the related functions cscant, tscanf, sscant, vscant, vtscant, and vsscanf controls how each function scans, converts, and stores its input fields. There must be enough address arguments for the given format specifiers; if not, the results are unpredict-able and likely disastrous. Excess address arguments (more than required by the format) are merely ignored.
b^
scanf often leads to unexpected results if you diverge from an expected pattern. You need to remember to teach scanf how to synchronize at the end of a line. The combination of gets or fgets followed by sscanf is safe and easy, and therefore preferred.
The format string is a character string that contains three types of objects: whitespace characters, non-whitespace characters, and format specifiers.
B The whitespace characters are blank, tab (\t) or newline (\n). If a ...scanf function encounters a whitespace character in the format string, it will read, but not store, all consecutive whitespace characters up to the next non-whitespace character in the input. □ The non-whitespace characters are all other ASCII characters except the percent sign (%). If a ...scanf function encounters a non-whitespace character in the format string, it will read, but not store, a matching non-whitespace character. □ The format specifiers direct the ...scanf functions to read and convert characters from the input field into specific types of values, then store them in the locations given by the address arguments.
Trailing whitespace is left unread (including a newline), unless explicitly matched in the format string.
Format specifiers
...scanf format specifiers have the following form:
% [*] [width] [FIN] [hlllL] type_character
Each format specifier begins with the percent character (%). After the % come the following, in this order:
| B an optional assignment-suppression | character, [ * ] |
B an optional width specifier, [widtli] B an optional pointer size modifier, [FIN] B an optional argument-type modifier, [li 111L] B the type character
Optional format
These are the general aspects of input formatting controlled by the
string components
optional characters and specifiers in the ...scanf format string:
Character
| or specifier | What it controls or specifies Suppresses assignment of the next input field. |
| width | Maximum number of characters to read; fewer characters might be read if the ...scanf function encounters a whitespace or unconvertible character. Overrides default size of address argument: N = near pointer F = far pointer |
| argument | Overrides default type of address argument: |
type h - short int / = long int (if the type character specifies an integer conversion) / = double (if the type character specifies a floating-point conversion) L = long double (valid only with floating-point conversions)
.scanftype
The follow^ing table lists the ...scanf type characters, the type of input
characters
| each, and in what format the | w^ill be stored. |
| expected by | input |
The information in this table is based on the assumption that no optional characters, specifiers, or modifiers (*, v^^idth, or size) were included in the format specifier. To see how the addition of the optional elements affects the ...scanf input, refer to the tables following this one.
Type characterExpected
| input | Type of argument |
Numerics dDecimal
| integer | Pointer to int (int *arg) |
DDecimal
| integer | Pointer to long (long *arg) |
oOctal
| integer | Pointer to int (int *arg) |
0Octal
| integer | Pointer to long (long *arg) |
Decimal,
| octal, or | Pointer to int (int *arg) |
hexadecimal
integer
1Decimal,
| octal, or | Pointer to long (long *arg) |
hexadecimal
integer
uUnsigned
| decimal | Pointer to unsigned int |
integer
(unsigned int *arg)
UUnsigned
| decimal | Pointer to unsigned long |
integer
(unsigned long *arg)
XHexadecimal
| integer | Pointer to int (int *arg) |
XHexadecimal
| integer | Pointer to int (int *arg) |
e, ERoating
| point | Pointer to float (float *arg) |
fHoating
| point | Pointer to float (float *arg) |
g,GFloating
| point | Pointer to float (float *arg) |
Characters s Character
| string | Pointer to array of characters (char arg[]) |
c Character
Pointer to character (char *arg) if a field width W is given along with the c-type character (such as %5c). Pointer to array of W characters (char arg[W])
%%
| character | No conversion done; % is stored. |
Pointers n
Pointer to int (int *arg). The number of characters read successfully up to %n is stored in this int.
Hexadecimal
| form | Pointer to an object (far* or near*) |
YYYY:ZZZZ
| or | 7op conversions default to the |
ZZZZ
pointer size native to the memory model.
Input fields
Any one of the follow^ing is an input field:
■ all characters up to (but not including) the next w^hitespace character ■ all characters up to the first one that cannot be converted under the current format specifier (such as an 8 or 9 under octal format) ■ up to n characters, where n is the specified field width
Conventions
Certain conventions accompany some of these format specifiers, as
| summarized | here. |
%c conversion This specification reads the next character, including a whitespace char-acter. To skip one whitespace character and read the next non-whitespace character, use %ls.
%Wc conversion (W= width specification) The address argument is a pointer to an array of characters; the array consists of Welements (char arg[W\).
%s conversion The address argument is a pointer to an array of characters (char argU).
The array size must be at least («+l) bytes, where n equals the length of string s (in characters). A space or new line terminates the input field. A null-terminator is automatically appended to the string and stored as the last element in the array.
%[searcti_set] conversion The set of characters surrounded by square brackets can be substituted for the s-type character. The address argument is a pointer to an array of characters (char arg[]).
These square brackets surround a set of characters that define a search set of possible characters making up the string (the input field).
If the first character in the brackets is a caret {^), the search set is inverted to include all ASCII characters except those between the square brackets. (Normally, a caret will be included in the inverted search set unless explicitly listed somewhere after the first caret.)
The input field is a string not delimited by whitespace. ...scanf reads the corresponding input field up to the first character it reaches that does not appear in the search set (or in the inverted search set). Two examples of this type of conversion are
% [abed] Searches for any of the characters a, b, c, and d in the input field. % [ "abed] Searches for any characters except a, h, c, and d in the input field.
You can also use a range facility shortcut to define a range of characters (numerals or letters) in the search set. For example, to catch all decimal digits, you could define the search set by using % [0123455789], or you could use the shortcut to define the same search set by using % [0-9].
To catch alphanumeric characters, use the following shortcuts:
| % [A-Z] | Catches all uppercase letters. |
% [0-9A-Za-z] Catches all decimal digits and all letters (uppercase and lowercase).
| % [A-FT-Z] | Catches all uppercase letters from A through f and from T through Z. |
The rules covering these search set ranges are straightforward:
■ The character prior to the hyphen (-) must be lexically less than the one after it. B The hyphen must not be the first nor the last character in the set. (If it is first or last, it is considered to just be the hyphen character, not a range definer.) B The characters on either side of the hyphen must be the ends of the range and not part of some other range.
Here are some examples where the hyphen just means the hyphen character, not a range between two ends:
| %[-+*/] | The four arithmetic operations |
| %[z-a] | The characters 2,-, and fl |
% [+0-9-A-Z] The characters + and - and the ranges 0-9 and A-Z % [+0-9A-Z-] Also the characters + and - and the ranges 0-9 and A-Z % [''-0-9+A-z] All characters except + and - and those in the ranges 0-9 and A-Z
%e, %E. %f, %g, and %G (floating-point) conversions Floating-point numbers in the input field must conform to the following generic format:
[+/-] ddddddddd [.] dddd [E I e] [+/-] ddd where [item] indicates that item is optional, and ddd represents decimal, octal, or hexadecimal digits.
INF = infinity; NAN =
In addition, +INF, -INF, +NAN, and -NAN are recognized as floating-
not a number
pQJj^j- numbers. Note that the sign and capitalization are required.
%d, %i, %o, %x, %D, %!, %0, %X, %c, %n conversions A pointer to unsigned character, unsigned integer, or unsigned long can be used in any conversion where a pointer to a character, integer, or long is allowed.
| The assignment-suppression | character is an asterisk (*); it is not to be |
Assignment-
confused with the C indirection (pointer) operator (also an asterisk).
suppression character
If the asterisk follows the percent sign (%) in a format specifier, the next input field will be scanned but will not be assigned to the next address argument. The suppressed input data is assumed to be of the type specified by the type character that follows the asterisk character.
The success of literal matches and suppressed assignments is not directly determinable.
Widtti specifiers
| The width specifier (n), a decimal integer, controls the maximum | number |
of characters that will be read from the current input field.
If the input field contains fewer than n characters, ...scanf reads all the characters in the field, then proceeds with the next field and format specifier.
If a whitespace or nonconvertible character occurs before width characters are read, the characters up to that character are read, converted, and stored, then the function attends to the next format specifier.
A nonconvertible character is one that cannot be converted according to the given format (such as an 8 or 9 when the format is octal, or a / or X when the format is hexadecimal or decimal).
Width
| specifier | How width of stored input is affected |
| n | Up to n characters are read, converted, and stored in the current address argument. |
Input-size and
The input-size modifiers (N and F) and argument-type modifiers (/z, /, and
argument-type
L) affect how the ...scanf functions interpret the corresponding address
modifiers
argument arglf.
F and N override the default or declared size of arg.
h, I, and L indicate which type (version) of the following input data is to be used (h = short, / = long, L = long double). The input data will be converted to the specified version, and the arg for that input data should point to an object of the corresponding size (short object for %h, long or double object for %l, and long double object for %L).
Modifier How conversion is affected
| F | Overrides default or declared size; arg interpreted as far pointer. |
| N | Overrides default or declared size; arg interpreted as near pointer. Cannot be used with any conversion in huge model. |
| h | For d, i, o, u, x types, convert input to short int, store in short object. For D, I, O, U, X types, no effect. For e, f, c, s, n, p types, no effect. |
| I | For d, i, 0, ii, x types, convert input to long int, store in long object. For e,f, g types, convert input to double, store in double object. For D, /, O, U, X types, no effect. For c, s, n, p types, no effect. |
| L | For e, f, g types, convert input to a long double, store in long double object. L has no effect on other formats. |
When scanf stops
scanf might stop scanning a particular field before reaching the normal
scanning
field-end character (whitespace), or might terminate entirely, for a variety of reasons.
scanf stops scanning and storing the current field and proceed to the next input field if any of the follow^ing occurs:
| ■ An assignment-suppression character in the format specifier; the current input field is scanned but not stored. | character C^) appears after the percent |
■ width characters have been read {width = w^idth specification, a positive decimal integer in the format specifier). ■ The next character read cannot be converted under the current format (for example, an A when the format is decimal). ■ The next character in the input field does not appear in the search set (or does appear in an inverted search set).
When scanf stops scanning the current input field for one of these reasons, the next character is assumed to be unread and to be the first character of the following input field, or the first character in a subsequent read operation on the input.
scanf will terminate under the following circumstances:
■ The next character in the input field conflicts with a corresponding non-whitespace character in the format string. ■ The next character in the input field is EOF.
D The format string has been exhausted.
If a character sequence that is not part of a format specifier occurs in the format string, it must match the current sequence of characters in the input field; scanf will scan but not store the matched characters. When a conflicting character occurs, it remains in the input field as if it were never read.
Return value
scanf returns the number of input fields successfully scanned, converted, and stored; the return value does not include scanned fields that were not stored.
If scanf attempts to read at end-of-file, the return value is EOF.
If no fields were stored, the return value is 0.
See also
Example
#include <stdio.h>
#include <conio.h>
int main(void)
{
char label [20],-
char name[20];
int entries = 0;
int loop, age;
double salary;
struct Entry_struct {
char name[20];
int age;
float salary;
} entry[20];
/* input a label as character string restricted to 20 characters */
printf("\n\nPlease enter a label for the chart: ");
scanf("%20s", label);
fflush(stdin); /* flush input stream in case of bad input */
/* input number of entries as integer */
printf("How many entries will there be? (less than 20) ");
scanf("%d", &entries);
/* flush the input stream in case of bad input */
fflush(stdin);
/* input a name, restricting input to only upper- or lowercase letters */
for (loop=0;loop<entries;++loop) {
printf("Entry %d\n", loop);
printf(" Name : ");
scanf("%[A-Za-z]", entry[loop].name);
fflush(stdin); /* flush input stream in case of bad input */
/* input an age as integer */
printfC Age : ");
scanf("%d", &entry [loop].age);
fflush(stdin); /* flush input stream in case of bad input */
/* input a salary as a float */
printfC Salary : ");
scanf("%f", &entry [loop].salary);
fflush(stdin); /* flush input stream in case of bad input */
}
/* input name, age, and salary as string, integer, and double */
printf("\nPlease enter your name, age and salary\n");
scanf("%20s %d %lf", name, &age, &salary) ;
/* print out the data that was input */
printf("\n\nTable %s\n" ,label),■
printf("Compiled by %s age %d $%15.21f\n", name, age, salary);
printfC \n") ;
for (loop=0;loop<entries;++loop)
printf("%4d I %-20s I %5d I %15.21f\n", loop + 1, entry[loop].name,
entry [loop].age, entry[loop].salary);
printfC ■ \n") ;
return 0;
Differences from modern implementations
Nothing recorded yet.
Modern references
These are search links, not yet checked by hand.
Extraction notes
- heading `scant` read as `scanf`
Stable link: /3.1/stdio.h/scanf/
· short form /3.1/scanf/