c primer plus最后一章的编程题中,调试时候发现下面代码总是多输出一次提示消息,百思不得其解
#include <stdio.h>
#define YANGLI 2.05
#define TIANCAI 1.15
#define HULUOBO 1.09
int main(void)
{
printf("Enter the vegetable you want: \n");
printf("a)yangji $2.05 b)tiancai $1.15\n");
printf("c)huluobo $1.09 q)quit\n");
char ch;
scanf("%c", &ch);
float yangji_w, tiancai_w, huluobo_w;
yangji_w = tiancai_w = huluobo_w = 0;
while ( ch != 'q')
{
int temp = 0;
switch (ch)
{
case 'a':
printf("enter the weight you want buy yangji: \n");
scanf("%d", &temp);
yangji_w += temp;
break;
case 'b':
printf("enter the weight you want buy tiancai: \n");
scanf("%d", &temp);
tiancai_w += temp;
break;
case 'c':
printf("enter the weight you want buy huluobo: \n");
scanf("%d", &temp);
huluobo_w += temp;
break;
default:
printf("%c\n", 10);
break;
}
printf("Enter the vegetable you want: \n");
printf("a)yangji $2.05 b)tiancai $1.15\n");
printf("c)huluobo $1.09 q)quit\n");
// ch = getchar();
scanf("%c", &ch);
}
printf("%f", yangji_w);
return 0;
}
经过调试发现每次都是多输出的那一次ch是一个换行符,
Enter the vegetable you want:
a)yangji $2.05 b)tiancai $1.15
c)huluobo $1.09 q)quit
a
enter the weight you want buy yangji:
1
Enter the vegetable you want:
a)yangji $2.05 b)tiancai $1.15
c)huluobo $1.09 q)quit
Enter the vegetable you want:
a)yangji $2.05 b)tiancai $1.15
c)huluobo $1.09 q)quit
Enter the vegetable you want:
a)yangji $2.05 b)tiancai $1.15
c)huluobo $1.09 q)
经过一番搜索之后得知,在case中输入数字的时候会自动添加一个换行符在最后,比如我输入2,c接受到的是2\n,然后scanf("%d", &tmp)只将2读取并赋值给了tmp,导致剩余了一个\n在内存中(我还没上车呢.jpg),然后等到下一个scanf("%c", &ch)时候,内存中有一个\n字符,而这里有需要读取一个字符,所以情投意合直接不需要用户输入了,自动开始了下一次巡回。
我这里解决的话就是在case之后加上一个getchar()把\n读取,清除缓存就好了,其它情况还需要具体问题具体分析,比如不止一个字符,可能就需要循环读取直到把缓存清空才可以.