yunshichen

我相信人生是值得活的,尽管人在一生中必须遭受痛苦,卑劣,残酷,不幸和死亡的折磨,我依然深信如此.但我认为人生不一定要有意义,只是对一些人而言,他们可以使人生有意义. ---J 赫胥黎

C语言速记 第三章 拾遗补阙

Chapter 3 拾遗补阙

3.1 标准输入的缓冲区   

    当你使用标准输入函数,如getchar,gets,scanf时,请注意缓冲区问题.简言之,当你使用如下函数时:
int c=getchar();
   
    编译器会将键盘输入的字符存储到系统的缓冲区,再从缓冲区返回一个字符给c变量.在这个语句,实际上你至少输入了两个字符(第二个字符是回车).这个回车符号保存在缓冲区里.当你再次使用getchar或者gets时,这些函数会检查缓冲区,发现缓冲区还有字符,于是就直接读取这个字符,而不是读入键盘输入.

    也就是说,这些函数实际上并不是读入键盘输入的字符,而是先检查缓冲区.请观察以下这个错误的例子:
    puts("Input a char:");
    
int c=getchar();

    puts(
"What char is it?");
    putchar(c);
    putchar(
'\n');

    c
=getchar();
    putchar(c);

    system(
"pause");

    这个程序的本意是从键盘输入两次字符并打印.但你会发觉控制台只让你输入一次字符就自动结束.原因是第二个getchar发现缓冲区还有字符(上一个getchar留下的回车符号),所以它不等键盘输入就直接返回.
   
    所以,为了确保程序运行正确,每次运行getchar,gets,scanf..等函数时,先清空标准输入的缓冲区,语法如下:
    fflush(stdin);

    这个例子会加深你的了解:
#include <stdio.h>
#include 
<stdlib.h>
#include 
<ctype.h>
#include 
<string.h>
#include 
<stdarg.h>
int main() {
    puts(
"Input a char:");
    
int c=getchar();//Experiment to input a line instead of a char , and comment fflush(stdin) to watch the reslut.
    puts("What char is it?");
    putchar(c);
    putchar(
'\n');

    fflush(stdin);

    
char s[20];
    puts(
"Input a line:");
    gets(s);

    puts(
"What line is it?");
    puts(s);

    fflush(stdin);

    system(
"pause");

    
return 0;
}





posted on 2008-05-01 15:09 Chenyunshi 阅读(333) 评论(0)  编辑 收藏 引用 所属分类: C/C++

只有注册用户登录后才能发表评论。
<2008年5月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

常用链接

留言簿(7)

随笔分类

随笔档案

文章分类

相册

搜索

最新评论

阅读排行榜

评论排行榜