在while循环中使用getchar()将语句打印两次。。怎样?
我有这样一个非常简单的程序在while循环中使用getchar()将语句打印两次。。怎样?,c,C,我有这样一个非常简单的程序 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"); scan
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;
}
我得到如下输出:
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
我的疑问是,为什么每次循环后都会打印两次“m在里面。按c继续”
提前感谢这是因为先前的
扫描
留下了\n
字符。当您输入一个数字并按Enter键时,一个附加的\n
字符将传递到标准输入缓冲区scanf
读取在缓冲区中留下的\n
号。在循环的下一次迭代中,getchar
读取\n
,然后按下任何字符,因此,m在中间。按下c继续打印两次,因为\n
不是c
将这段代码放在scanf
语句后面,然后在while
循环中使用换行符
while(getchar() != '\n');
这将消耗任何数量的\n
有关getchar的行为的详细说明,请阅读。
最后的代码应该是
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;
}
scanf读取输入后,缓冲区中仍有一个“\n”
,您必须清除它,否则它将在下次被getchar读取,因为它是!=”c'
它将再次提示:
试试这个:
printf("choose a number\n");
scanf(" %d",&n);
char c;
while (c = getchar != '\n' && c != EOF); // clear the buffer
printf("choose a number\n");
scanf(" %d",&n);
char c;
while (c = getchar != '\n' && c != EOF); // clear the buffer