Scanf 在 C 中不工作
Scanf is not working in C
我想弄清楚为什么第二个 scanf 对我不起作用。这是代码:
#include <stdio.h>
int main() {
char n;int p;
printf("Enter the number: ");
scanf("%d",&p);
if(p==1) {
printf("Enter a character: ");
scanf("%c",&n);
}
}
在此程序中,第二个 scanf("%c",&n)
不起作用。我究竟做错了什么?上面程序的输出是:
Enter a number: 1
Enter a charter:
它正在从编译器中出来。
这是因为之前的scanf()
在输入缓冲区中留下了一个换行符。告诉 scanf 忽略所有白色 spaces 的简单修复:
scanf(" %c",&n); //Note the space before %c
格式字符串中的任何白色space指令(space、\n
等)告诉scanf忽略输入中任意数量的白色space。
来自 scanf()
手册:
A sequence of white-space characters (space, tab, newline,
etc.; see isspace(3)). This directive matches any amount of
white space, including none, in the input.
前面的 scanf()
留下尾随换行符 \n
。边做边吃
scanf(" %c",&n);
我想弄清楚为什么第二个 scanf 对我不起作用。这是代码:
#include <stdio.h>
int main() {
char n;int p;
printf("Enter the number: ");
scanf("%d",&p);
if(p==1) {
printf("Enter a character: ");
scanf("%c",&n);
}
}
在此程序中,第二个 scanf("%c",&n)
不起作用。我究竟做错了什么?上面程序的输出是:
Enter a number: 1
Enter a charter:
它正在从编译器中出来。
这是因为之前的scanf()
在输入缓冲区中留下了一个换行符。告诉 scanf 忽略所有白色 spaces 的简单修复:
scanf(" %c",&n); //Note the space before %c
格式字符串中的任何白色space指令(space、\n
等)告诉scanf忽略输入中任意数量的白色space。
来自 scanf()
手册:
A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
前面的 scanf()
留下尾随换行符 \n
。边做边吃
scanf(" %c",&n);