gpt4 book ai didi

c - C 中 scanf 函数的格式说明符中 %c 规范之前的空格

转载 作者:行者123 更新时间:2023-12-02 06:53:36 24 4
gpt4 key购买 nike

当我在 scanf() 函数的格式字符串中的 %d%c 规范之间不包含空格时以下程序,并在运行时输入为“4 h”,然后输出为“Integer = 4 and Character=.

在这种情况下,变量 "c" 究竟是如何接受输入的,如果我在 %d%c 之间包含一个空格,它有什么区别 规范?

代码

#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 中,有三个没有:

  • %n — 到目前为止已经处理了多少个字符
  • %[…] — 扫描集
  • %c — 读取一个字符。

(POSIX增加了第四个,%C,相当于%lc。)

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

%d%c 之间添加空格意味着在读取整数之后和读取(不是空格)字符之前跳过可选的空格。

请注意,格式字符串中的文字字符(空格除外 - 例如,"X%dY" 中的 XY >) 不要跳过空格。匹配此类字符也不算成功转换;它们不会影响 scanf() 等的返回值。

关于c - C 中 scanf 函数的格式说明符中 %c 规范之前的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36504135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com