C语言的缓存区

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读取,清除缓存就好了,其它情况还需要具体问题具体分析,比如不止一个字符,可能就需要循环读取直到把缓存清空才可以.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值