C语言中scanf函数研究

先看程序,再解释!
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i;
    char c[5]={0};
    for(i = 0; i < 3; i++)
    {
         scanf("%c",&c[i]);  //  第一个scanf
         printf("kkk ");
    }
    for (i=0; i<5; i++)
    {
          printf("%c",c[i]);
    }    
     printf("\nhello world!");
     printf("\nhello world!\n");
     //fflush(stdin);
     for(i = 3; i < 5; i++)
    {
          scanf(" %c",&c[i]);  // 第二个scanf
    }
     for (i=0; i<5; i++)
    {
          printf("%c",c[i]);
    }
    system("pause");
    return 0;
}

情景1:
       输入:
               abcdefghi回车
       输出:
               kkk kkk kkk abc
               hello world!
               hello world!
               abcde
       分析:我们在窗口中输入一串字符后,这些字符被送入一个缓冲区,然后scanf从缓冲区读取字符(因为
                输入格式为%c,所以是字符),读一个后便执行 printf("kkk ") 一次,因此有3个kkk 。
                但第2个scanf处并没有在窗口中进行字符输入,是因为scanf从缓冲区自动读取了de 这2个字符
                。要想在此处可以进行输入可以采用fflush()函数清空缓冲区。

情景2:
        对于字符,如果按了回车键,则字符'\n'会也会被赋值给变量。
        如输入:a回车,则c[0]='a' c[1]='\n',对于上面的程序,循环还没有结束,所以需要继续输入。
        例如:
               输入:
                        a回车
           屏幕显示:
                         a
                         kkk kkk 
           继续输入:
                          b回车
            屏幕显示:
                          a
                          kkk kkk b
                          kkk a
                          b
                          hello word!
                          hello world!
             继续输入:
                           cde
             屏幕显示:
                          a
                          kkk kkk b
                          kkk a
                          b
                          hello word!
                          hello world!
                          cde
                          a
                          bcd

转载于:https://my.oschina.net/ctf/blog/135645

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值