scanf要求两个值而不是一个

and*_*imo 3 c scanf

当我编译这段代码时,当我选择A时,它会导致scanf要求两次值.我在这里缺少什么?

这不是第一次遇到这种情况,所以我怀疑我没有抓住scanf的基本内容.

#include <stdio.h>
#include <stdlib.h>

int main()
{

char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");

scanf("%c", &choice);

switch (choice)
{
case 'A':
    {
        int a =0;
        printf("you've chosen menu A\n");
        printf("enter a number\n");
        scanf("%d\n", &a);
        printf("%d\n", a);
    }
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
}

return 0;

}
Run Code Online (Sandbox Code Playgroud)

Moh*_*ain 6

scanf("%d\n", &a); 应该 scanf("%d", &a);

另请阅读相关问题.

在前一种情况下,读取一个整数并存入a后,scanf参数字符串不会耗尽.看一下\n,scanf将消耗它看到的所有空格(换行符,制表符,间隔等)(并且将保持阻塞状态),直到遇到非空白字符.在遇到非空白字符时scanf会返回.

学习:不要在scanf中使用空格,换行符等作为尾随字符.如果空格字符位于参数字符串的开头,则scanf可能仍会跳过任意​​数量的空格字符,包括零字符.但是当空白是一个尾随字符时,它会占用你的新行字符,除非你键入一个非空白字符并点击返回键.