Go to the first, previous, next, last section, table of contents.

String Input Conversions

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:

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:

Matches a string of up to 25 digits.
Matches a string of up to 25 square brackets.
`%25[^ \f\n\r\t\v]'
Matches a string up to 25 characters long that doesn't contain any of the standard whitespace characters. This is slightly different from `%s', because if the input begins with a whitespace character, `%[' reports a matching failure while `%s' simply discards the initial whitespace.
Matches up to 25 lowercase characters.

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.