关于c语言当中while循环里的scanf()引发的缓冲区问题

关于c语言当中while循环里的scanf()引发的缓冲区问题

在第一堂c语言课程中利用while循环中加入scanf的方式,连续输入学生信息,但是循环只能进行一次,首先来看代码:

快捷键

  • 加粗 Ctrl + B
  • 斜体 Ctrl + I
  • 引用 Ctrl + Q
  • 插入链接 Ctrl + L
  • 插入代码 Ctrl + K
  • 插入图片 Ctrl + G
  • 提升标题 Ctrl + H
  • 有序列表 Ctrl + O
  • 无序列表 Ctrl + U
  • 横线 Ctrl + R
  • 撤销 Ctrl + Z
  • 重做 Ctrl + Y
### 代码块
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    struct student{

        char name[100];
        float score;
    };
    char c='Y';
    int n;
    while('Y'==c)
    {
        struct student stu1;
        printf("You can enter the name:\n");
        scanf("%s",&stu1.name);
        printf("You cna enter the score:\n");
        scanf("%f",&stu1.score);
        n=(int)(stu1.score-50)/10;
        switch (n)
        {
        case 5:
            printf("%s best\n",stu1.name);
            break;
        case 4:
            printf("%s good\n",stu1.name);
            break;
        case 3:
            printf("%s ordinary\n",stu1.name);
            break;
        case 2:
            printf("%s bad\n",stu1.name);
            break;
        case 1:
            printf("%s very bad\n",stu1.name);
            break;
        case 0:
            printf("%s are you kidding me?\n",stu1.name);
            break;
        default:
            printf("ERROR!\n");


        }
        printf("Do you want to continue to enter?(Y or N)\n");
        scanf"%c",&c);

    }


    return 0;
}

#

输出结果如下:
You can enter the name:
asad
You cna enter the score:
56
asad are you kidding me?
Do you want to continue to enter?(Y or N)

Process returned 0 (0x0) execution time : 4.810 s
Press any key to continue.
可以看到,循环只进行了一次,其原因为,在输入c的scanf函数之前输入学生成绩的scanf处,输入形式为:56回车
此时,缓冲区内有56和回车两个,56被学生成绩读入,而回车作为字符被下一个scanf的c读入,因此c的值总为回车,而不是Y,循环只进行一次。
关于scanf函数缓冲区的具体讲解,请看:https://blog.csdn.net/peixiaoge/article/details/53377880
while循环scanf的类似问题:https://blog.csdn.net/wei_cheng18/article/details/71056413

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值