zoukankan      html  css  js  c++  java
  • 缓冲思想

           缓冲是计算机领域非常常见的一种思想。其主要目的是为了平衡设备之间的能力差异。从硬件到软件,缓冲思想无处不在。

           CPU的Cache,绘图时的双缓冲方法等等都是缓冲的具体实践。

    C语言中的fflush(FILE      *stream)函数。

    fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃

       fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上。

    下面的程序从不停地从键盘读取数据到int data中,同时显示data的值。

    #include <stdio.h>

    int main()

    {

             int data = 0;

             while(1){

                       scanf("%d", &data);

                       printf("%d\n", data);

             }

             return 0;

    }

    输入整数时不会出现异常,但是当用户输入字母时(例如a),a就在缓冲区中始终无法被读取,而因为缓冲区中有数据,scanf()就不会等待用户的输入,因此造成了死循环。

    在scanf()后加上fflush(stdin)即可解决问题。

    #include <stdio.h>

    int main()

    {

             int data = 0;

             while(1){

                       scanf("%d", &data);

                       printf("%d\n", data);

                       fflush(stdin);

             }

             return 0;

    }

           同时也可以自己写代码来替代fflush(stdin)的功能:

    #include <stdio.h>

    int main()

    {

             int data = 0;

             int flag;

             while(1){

                       scanf("%d", &data);

                       printf("%d\n", data);

                       //fflush(stdin);

                       while((c = getchar()) != '\n' && c !=EOF)

                                ;

             }

             return 0;

    }

  • 相关阅读:
    企业微信的部门长度问题
    MVC中view与controller传json数据
    jQuery.extend()、jQuery.fn.extend()扩展方法示例详解
    程序员成长思维:把自己当做产品来发展
    发展你的兴趣,而不是跟随你的兴趣
    领导力:不要做个“好人”
    Nginx性能优化
    【.NET与树莓派】上手前的一些准备工作
    php curl时遇到Can't load the certificate "..." and its private key: OSStatus -25299的问题
    ASCII码字符对照表
  • 原文地址:https://www.cnblogs.com/johnpher/p/2570647.html
Copyright © 2011-2022 走看看