This section describes the scanf
input conversions for reading
string and character values: `%s', `%[', and `%c'.
You have two options for how to receive the input from these conversions:
char *
.
Warning: To make a robust program, you must make sure that the
input (plus its terminating null) cannot possibly exceed the size of the
buffer you provide. In general, the only way to do this is to specify a
maximum field width one less than the buffer size. If you
provide the buffer, always specify a maximum field width to prevent
overflow.
scanf
to allocate a big enough buffer, by specifying the
`a' flag character. This is a GNU extension. You should provide
an argument of type char **
for the buffer address to be stored
in. See section Dynamically Allocating String Conversions.
The `%c' conversion is the simplest: it matches a fixed number of characters, always. The maximum field with says how many characters to read; if you don't specify the maximum, the default is 1. This conversion doesn't append a null character to the end of the text it reads. It also does not skip over initial whitespace characters. It reads precisely the next n characters, and fails if it cannot get that many. Since there is always a maximum field width with `%c' (whether specified, or 1 by default), you can always prevent overflow by making the buffer long enough.
The `%s' conversion matches a string of non-whitespace characters. It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something. It stores a null character at the end of the text that it reads.
For example, reading the input:
hello, world
with the conversion `%10c' produces " hello, wo"
, but
reading the same input with the conversion `%10s' produces
"hello,"
.
Warning: If you do not specify a field width for `%s', then the number of characters read is limited only by where the next whitespace character appears. This almost certainly means that invalid input can make your program crash--which is a bug.
To read in characters that belong to an arbitrary set of your choice, use the `%[' conversion. You specify the set between the `[' character and a following `]' character, using the same syntax used in regular expressions. As special cases:
The `%[' conversion does not skip over initial whitespace characters.
Here are some examples of `%[' conversions and what they mean:
One more reminder: the `%s' and `%[' conversions are dangerous if you don't specify a maximum width or use the `a' flag, because input too long would overflow whatever buffer you have provided for it. No matter how long your buffer is, a user could supply input that is longer. A well-written program reports invalid input with a comprehensible error message, not with a crash.
Go to the first, previous, next, last section, table of contents.