|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#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会打印两次?
因为你没有清空缓冲区,这样缓冲区内会剩一个'\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;
- }
复制代码
|
|