打印问题
#include <stdio.h>#include <ctype.h>
#define ARTICHOKE 2.05
#define BEET 1.15
#define CARROT 1.09
int main(void)
{
char ch;
int sum_pound1 = 0, sum_pound2 = 0,sum_pound3 = 0;
int pound1,pound2,pound3;
printf("a) artichoke b) beet\n");
printf("c) carrot q) quit\n");
printf("Please enter the wodld.\n");
while ((ch = getchar()) != 'q')
{
ch = tolower(ch);
switch (ch)
{
case 'a':
printf("Please enter the pound of artichoke.\n");
scanf_s("%d", £1);
sum_pound1 += pound1;
break;
case 'b':
printf("Please enter the pound of been.\n");
scanf_s("%d", £2);
sum_pound2 += pound2;
break;
case 'c':
printf("Please enter the pound of carrot.\n");
scanf_s("%d", £3);
sum_pound3 += pound3;
break;
default:
break;
}
printf("Please enter the world again.\n");
}
getchar();
return 0;
}
这个程序为什么最后的printf会打印两次? 哪一个printf打印两次呀,讲一下
刘邦 发表于 2019-4-8 21:13
哪一个printf打印两次呀,讲一下
最后一个printf(“Please enter the world again.\n”);这个
不好意思,试了很多次这个语句放哪都不行,都会打印两次,帮不上你了,建议你重写一下
因为你没有清空缓冲区,这样缓冲区内会剩一个'\n',
第二次就直接读入'\n'了,所以会额外循环一遍
在第二次读之前清空缓冲就好
#include <stdio.h>
#include <ctype.h>
#define ARTICHOKE 2.05
#define BEET 1.15
#define CARROT 1.09
int main(void)
{
char ch;
int sum_pound1 = 0, sum_pound2 = 0,sum_pound3 = 0;
int pound1,pound2,pound3;
printf("a) artichoke b) beet\n");
printf("c) carrot q) quit\n");
printf("Please enter the wodld.\n");
setbuf(stdin,NULL);
while ((ch = getchar()) != 'q')
{
switch (ch)
{
case 'a':
printf("Please enter the pound of artichoke.\n");
scanf_s("%d", £1);
sum_pound1 += pound1;
break;
case 'b':
printf("Please enter the pound of been.\n");
scanf_s("%d", £2);
sum_pound2 += pound2;
break;
case 'c':
printf("Please enter the pound of carrot.\n");
scanf_s("%d", £3);
sum_pound3 += pound3;
break;
default:
break;
}
printf("Please enter the world again.\n");
while ((ch=getchar())!='\n' && ch!=EOF); //清空缓冲区
}
getchar();
return 0;
} 流弊呀兄弟
页:
[1]