我有一个非常简单的程序
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继续”在每次循环后都会被打印两次?
提前致谢
答案 0 :(得分:4)
这是因为之前的\n
遗留了scanf
个字符。输入数字并按 Enter 键时,会将另一个\n
字符传递给标准输入缓冲区。 scanf
读取nuber在缓冲区中留下\n
。在循环getchar
的下一次迭代中,在您按下任何字符之前读取\n
,因此m inside while.Press c to continue
打印两次\n
不是c
。
将此代码段放在scanf
循环中的while
语句之后,以占用换行符
while(getchar() != '\n');
这将占用任意数量的\n
有关getchar
阅读this answer的行为的更详细说明
你的最终代码应该是
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;
}
答案 1 :(得分:2)
在scanf读取输入后,缓冲区中仍然有一个'\n'
,你必须清除它,否则下次将被getchar重写,因为它是!= 'c'
它会再次提示:< / p>
试试这个:
printf("choose a number\n");
scanf(" %d",&n);
char c;
while (c = getchar != '\n' && c != EOF); // clear the buffer
答案 2 :(得分:1)
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");
}
}
}