键盘缓冲区对getchar(),fgets()的影响

在调用getchar(),fgets()的时候,可以一次输入多个字符,超出getcha()或者fgets()的限制。但这些字符会放到键盘缓冲区中,只有在输入回车键的时候,才会通知getchar()或者fgets()来读取缓冲区的内容。但是getchar()一次只能从缓冲区中读一个字符,所以如果你连续执行两个getchar(),在第一个getchar()中输入超过两个字符,在执行第二个getchar()时,他会从缓冲区读取剩余的字符,而不会在屏幕出现光标,给你机会输入新的字符。比如如下代码可以体会键盘缓冲区的作用:

#include <stdio.h>

int main()
{
    char c;
    //int c;
    printf("enter a char:\n");
    c = getchar();//type more than  1 char, see what will happen
    printf("char entered:\n");
    //putchar(c);
    printf("%c\n",c);//auto cast, convert int c to char c?
    //printf("sizeof c is: %zd",sizeof (c));
    c = getchar();//if you type more than 1 char in the first input, this time, it will get the char
                  //from buffer, you will have no chance to type again.

    printf("second char entered:\n");
    printf("%c\n",c);
    return 0;

}

再比如下边的程序:

/* fgets3.c -- using fgets()
 *
 * when test, type 123456789, and then run it again, type 12345678, see the difference.
 *
 * Note: fgets read from the buffer, if it can't read all chars into words a time, it will
 * continue from where it left last time until match \n.
 *
 *
 * */
#include <stdio.h>
#define STLEN 10

int main(void)
{
    char words[STLEN];
    int i;

    puts("Enter strings (lenth between 11 and 20):");
    fgets(words,STLEN,stdin);
    puts("the first 9 char you type is:\n");
    fputs(words,stdout);
    //puts(words);
    puts("the rest char you type is: \n");
    getchar();//comment this line, see the difference when you type 123456789\n every time.it also read from the buffer, supportsing you type 123456789\n, the first fgets will
               //read 123456789 into words, append a \0, the \n reamin in buffer, getchar() will read
               // \n from the buffer, then the second fgets() will get input from stand in instead of buffer
               //
    fgets(words,STLEN,stdin);
    fputs(words,stdout);
    puts("done");


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值