C中scanf函数的格式说明符中%c规范之前的空格 [英] Whitespace before %c specification in the format specifier of scanf function in C
问题描述
当我在%d
和%c
规范之间不包括空格时, scanf()
函数在以下程序中运行,并在运行时输入 4 h,则输出为 Integer = 4 and Character =。
When I don't include white space between %d
and %c
specification in the format string of scanf()
function in the following program, and give input during run-time as "4 h", then the output is "Integer = 4 and Character= .
在这种情况下,变量 c
到底有多精确?如果我在%d
和%c
规范?
How exactly variable "c"
takes the input in this case and what difference does it make if i include a white space between %d
and %c
specification ?
代码
Code
#include <stdio.h>
int main()
{
char c;
int i;
printf("Enter an Integer and a character:\n");
scanf("%d %c",&i,&c);
printf("Integer = %d and Character = %c\n",i,c);
getch();
}
推荐答案
如果阅读了规范对于 scanf()
会很小心,大多数格式说明符会跳过前导空格。在标准C中,有三个没有:
If you read the specification for scanf()
carefully, most format specifiers skip leading white space. In Standard C, there are three that do not:
-
%n
到目前为止,已经处理了许多字符 -
%[…]
—扫描集 -
%c
—读一个字符。
%n
— how many characters have been processed up to this point%[…]
— scan sets%c
— read a character.
(POSIX添加了第四个, %C
,相当于%lc
。)
(POSIX adds a fourth, %C
, which is equivalent to %lc
.)
输入的空白字符(由 isspace
指定)将被跳过,除非转换规范中包含 [
, c
, C
或 n
转换说明符。
Input white-space characters (as specified by
isspace
) shall be skipped, unless the conversion specification includes a[
,c
,C
, orn
conversion specifier.
在%d
和%c
表示在读取整数之后且在读取(不是空白)字符之前跳过了可选的空白。
Adding the space between %d
and %c
means that optional white space is skipped after the integer is read and before the (not white space) character is read.
请注意,格式字符串中的文字字符(空格除外),例如 X
和 Y
在 X%dY
中)不要跳过空白。匹配这些字符也不算是成功的转换。它们不会影响 scanf()
等的返回值。
Note that literal characters in a format string (other than white space — for example, the X
and Y
in "X%dY"
) do not skip white space. Matching such characters does not count as a successful conversion either; they do not affect the return value from scanf()
et al.
这篇关于C中scanf函数的格式说明符中%c规范之前的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!