Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The scanf 'maximum field width' includes whitespace?

Suppose we have

int n;
sscanf(" 42", "%2d", &n);

Should n be 4 (the whitespace accounted for by the "%2d") or 42 (whitespace ignored, making scanf read 3 characters)?

ideone implementation reads 3 characters

like image 269
pmg Avatar asked May 09 '26 16:05

pmg


1 Answers

The POSIX specification for sscanf() is fairly clear about the processing:

The format is a character string, … composed of zero or more directives. Each directive is composed of one of the following: one or more white-space characters (<space>, <tab>, <newline>, <vertical-tab>, or <form-feed>); an ordinary character (neither '%' nor a white-space character); or a conversion specification. Each conversion specification is introduced by the character '%' [CX] ⌦ or the character sequence "%n$", ⌫ after which the following appear in sequence:

A directive that is a conversion specification defines a set of matching input sequences, as described below for each conversion character. A conversion specification shall be executed in the following steps.

Input white-space characters (as specified by isspace) shall be skipped, unless the conversion specification includes a [, c, C, or n conversion specifier.

An item shall be read from the input, unless the conversion specification includes an n conversion specifier. An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence. The first byte, if any, after the input item shall remain unread. If the length of the input item is 0, the execution of the conversion specification shall fail; this condition is a matching failure, unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.

If white space is skipped by a conversion specification (%…), it is not counted as part of the field width; the skipping occurs before any counting does.

The equivalent specification in C11 §7.21.6.2 The fscanf function is very similar (but it doesn't include the 'C extension' markup, of course).

like image 134
Jonathan Leffler Avatar answered May 11 '26 06:05

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!