gpt4 book ai didi

c - 无法在下面的代码中为 Char 变量赋值?

转载 作者:行者123 更新时间:2023-11-30 20:14:46 25 4
gpt4 key购买 nike

对这个C程序感到困惑,当我按这个顺序执行时,这个程序并不要求选择作为输入,但是如果我在选择之后放置整数输入(inputNum)语句,则询问选择输入是否有效,但整数输入不接受输入值

      int main()
{ int inputNum; char choice='A';

printf("Please enter number : ");
scanf("%d",&inputNum);

printf("\nEnter (N/n) to STOP ADDING : ");
scanf("%c",&choice);
printf("\nChoice is : %c\n",choice);

return 0;
}

最佳答案

这就是发生的事情。

      printf("Please enter number : ");
scanf("%d",&inputNum);

当它运行时,系统会提示您输入一个数字,然后您当然会按回车键来刷新输入缓冲区。这会在其中留下一个 \n (换行符)字符,该字符由以下方式读取:

     printf("\nEnter (N/n) to STOP ADDING : ");
scanf("%c",&choice);

因此程序进入Choice is :并留下一个空行——这就是放入choice\n

一种解决方案是使用;

scanf("%*c%c", &choice);

* 告诉 scanf() 丢弃该字段,在本例中是上次输入中剩余的换行符。

if I put Integer Input (inputNum) statement after choice asking choice input is working

需要注意的是,换行符问题不会影响 %d 次扫描,因为这些会跳过前导空格。因此,如果您在程序中要求两个整数而不是 int 和 char,则无需手动跳过换行符即可工作。根据 POSIX man page for fscanf 中重复的 ISO C 99 标准草案的声明,相同的逻辑适用于大多数类型的输入。 :

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

这个“除非”当然适用于 %c

关于c - 无法在下面的代码中为 Char 变量赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588350/

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