在调用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");
}