[英]Using getchar() in a while loop, prints a statement twice.. how?
I have a very simple program like this 我有一个非常简单的程序
int main()
{
int opt;
int n;
int flag = 1;
while(flag)
{
printf("m inside while.Press c to continue\n");
if((opt = getchar())== 'c')
{
printf("choose a number\n");
scanf(" %d",&n);
switch(n)
{
case 0:
printf("m zero\n");
break;
case 1:
printf("entered one\n");
break;
case 3:
printf("m exit\n");
flag = 0;
break;
}
printf("m broke\n");
}
}
printf("m out\n");
return 0;
}
I get output like this: 我得到这样的输出:
m inside while.Press c to continue
c
choose a number
1
entered one
m broke
m inside while.Press c to continue
m inside while.Press c to continue
c
choose a number
My doubt is why "m inside while.Press c to continue" gets printed twice after every loop?? 我的疑问是为什么“m inside while.Press c to continue”在每次循环后被打印两次?
Thanks in advance 提前致谢
This is because of \\n
character left behind by previous scanf
. 这是因为之前的
scanf
留下了\\n
字符。 When you input a number and press Enter key, an additional \\n
character passed to the standard input buffer. 输入数字并按Enter键时,会将另一个
\\n
字符传递给标准输入缓冲区。 scanf
reads that nuber leaving behind \\n
in the buffer. scanf
读取nuber在缓冲区中留下\\n
。 On next iteration of loop getchar
reads \\n
before pressing any character by you and hence m inside while.Press c to continue
printed twice as \\n
is not c
. 在循环的下一次迭代中,
getchar
在你按任何字符之前读取\\n
,因此m inside while.Press c to continue
打印两次,因为\\n
不是c
。
Place this snippet of code just after the scanf
statement in your while
loop to eat up the newline characters 将这段代码放在
while
循环中的scanf
语句之后,以占用换行符
while(getchar() != '\n');
This will eat up any number of \\n
. 这会吃掉任何数量的
\\n
。
For more detailed explanation on the behavior of getchar
read this answer . 有关
getchar
行为的更详细说明,请阅读此答案 。
You final code should be 你最后的代码应该是
int main()
{
int opt;
int n;
int flag = 1;
while(flag)
{
printf("m inside while.Press c to continue\n");
if((opt = getchar())== 'c')
{
printf("choose a number\n");
scanf(" %d",&n);
while(getchar() != '\n');
switch(n)
{
case 0:
printf("m zero\n");
break;
case 1:
printf("entered one\n");
break;
case 3:
printf("m exit\n");
flag = 0;
break;
}
printf("m broke\n");
}
}
printf("m out\n");
return 0;
}
After scanf reads the input there is a '\\n'
still in the buffer you have to clear it otherwise it will be readed by getchar in the next time and as it's != 'c'
it will prompt again: 在scanf读取输入后,缓冲区中仍然有一个
'\\n'
,你必须清除它,否则它将在下一次由getchar重写,因为它是!= 'c'
它会再次提示:
Try this : 试试这个 :
printf("choose a number\n");
scanf(" %d",&n);
char c;
while (c = getchar != '\n' && c != EOF); // clear the buffer
while(flag)
{
printf("m inside while.Press c to continue\n");
while((opt=getchar()) != '\n') {
if(opt == 'c')
{
printf("choose a number\n");
scanf(" %d",&n);
switch(n)
{
case 0:
printf("m zero\n");
break;
case 1:
printf("entered one\n");
break;
case 3:
printf("m exit\n");
flag = 0;
break;
}
printf("m broke\n");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.