• c语言学习(4)


    fflush  stdin 的使用

    原文: https://www.cnblogs.com/CheeseIce/p/10630338.htmlc

    ------------------------------------

    fflush()的作用是用来刷新缓冲区;

    fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃;stdin是standard input的缩写,即标准输入,一般是指键盘;标准输入缓冲区即是用来暂存从键盘输入的内容的缓冲区。

    fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西强制打印到标准输出设备上。standard output 的缩写,即标准输出,一般是指显示器;标准输出缓冲区即是用来暂存将要显示的内容的缓冲区。

    一:

    复制代码
     1 #include "stdafx.h"
     2 #include<stdlib.h>
     3 #include<stdio.h>
     4  
     5 #pragma warning(disable:4996)
     6  
     7 using namespace std;
     8  
     9 int _tmain(int argc, _TCHAR* argv[])
    10 {
    11     int a;
    12     char c;
    13     scanf("%d", &a);
    14     c = getchar();
    15  
    16     printf("a=%d,c=%c", a, c);
    17  
    18     return 0;
    19 }
    复制代码

    二:

    复制代码
     1 #include "stdafx.h"
     2 #include<stdlib.h>
     3 #include<stdio.h>
     4  
     5 #pragma warning(disable:4996)
     6  
     7 using namespace std;
     8  
     9 int _tmain(int argc, _TCHAR* argv[])
    10 {
    11     int a;
    12     char c;
    13     scanf("%d", &a);
    14     fflush(stdin);
    15     c = getchar();
    16  
    17     printf("a=%d,c=%c", a, c);
    18  
    19     return 0;
    20 }
    复制代码

    解释:

    对比上面的代码,代码一没有清空输入缓冲区,回车时,将123赋值给a,缓冲区剩下abc,接着执行getchar(),发现缓冲区有内容,就无需等待用户输入,直接读取了,将'a'赋给c。代码二执行到fflush(),清空缓冲区,getchar()发现缓冲区没有内容,需要等待用户输入,所以必须输入两次。

  • 相关阅读:
    《Spring2之站立会议1》
    《Spring1之第十次站立会议》
    《Spring1之第九次站立会议》
    《Spring1之第八次站立会议》
    《Spring1之第七次站立会议》
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/oxspirt/p/13511325.html
Copyright © 2020-2023  润新知