c - scanf 'maximum field width' 包含空格?

标签 c language-lawyer standards

假设我们有

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

n 应该是 4(“%2d”所占的空格)还是 42(忽略空格,使 scanf 读取 3 个字符)?

ideone implementation读取 3 个字符

最佳答案

sscanf() 的 POSIX 规范 对处理过程相当清楚:

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.

如果转换规范 (%…) 跳过了空白,则它不计入字段宽度;跳过发生在任何计数之前。

C11 中的等效规范 §7.21.6.2 The fscanf function非常相似(当然,它不包括“C 扩展”标记)。

关于c - scanf 'maximum field width' 包含空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55581903/

相关文章:

c - 如何在 Visual Studio 代码中添加 gtk 库?

c - 展开链接列表中的内存开销?

c - 以下声明在 ANSI C 中有效吗?它是否有效?

c++ - 跨子对象边界的指针算法

r - 多个变量的组均值和标准差

android - Eclipse 索引器没有找到使用 android ndk 的函数

c++ - 我可以在下面的代码中使用任何编译器标志来报告有关 UB 的警告吗?

C++标准写法: Does "through all iterators in the range" imply sequentiality?

c - 这样的代码合法吗?

c - openCL Kernel计算Pi不是正确的值