Scanf在C中不起作用 [英] Scanf is not working in C
本文介绍了Scanf在C中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试弄清为什么第二个scanf对我不起作用.这是代码:
I am trying to work out why the second scanf is not working for me. Here is the code:
#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)
不起作用.我究竟做错了什么?上面程序的输出是:
In this program the second scanf("%c",&n)
is not working. What am I doing wrong? The output of above program is:
Enter a number: 1
Enter a charter:
它是从编译器中出来的.
It is coming out of compiler.
推荐答案
这是因为先前的 scanf()
在输入缓冲区中留下了换行符.一个简单的解决方法,告诉scanf忽略所有空格:
It's because the previous scanf()
left a newline in the input buffer. A simple fix to tell scanf to ignore all the whitespaces:
scanf(" %c",&n); //Note the space before %c
格式字符串中的任何空格指令(空格, \ n
等)都告诉scanf忽略输入中任意数量的空格.
Any whitespace directive ( space, \n
etc) in the format string tells scanf ignore any number of whitespaces in the input.
来自 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在C中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文