fflush(stdout)和fflush(stdin)

fflush是一个在C语言标准输入输出库中的函数,功能是冲洗流中的信息,该函数通常用于处理磁盘文件。fflush()会强迫将缓冲区内的数据写回参数stream 指定的文件中。

1、fflush(stdout)

fflush(FILE p)是把FILEp指向的流的输出立即写入并清空,所以加上fflush(stdout)就是立即显示到屏幕上。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void main()
{
        char str[20];
        pid_t pid=getpid();
        printf("my id is :%d",pid);
        fflush(stdout);     // if delete this line, we can't see the pid we want
        sprintf(str,"kill %d\n",pid);
        system(str);
}

这个程序若没有fflush(stdout)就不会看到pid的输出。

2、fflush(stdin)

第一个程序输入123abc+回车

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a;
    char c;
   
    scanf("%d", &a);
    c = getchar();

    printf("a = %d, c = %c \n", a, c);

    return 0;
}

请添加图片描述

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a;
    char c;
   
    scanf("%d", &a);
    fflush(stdin);
    c = getchar();

    printf("a = %d, c = %c \n", a, c);

    return 0;
}

其实,在这里没有区别,因为我实在Linux平台下编译的。这也是我后来才知道的,大家可以参考一下别人的解释

在windows VC下fflush(stdin)是可以实现的,但是linux下不可以。 C标准规定fflush()函数是用来刷新输出(stdout)缓存的。对于输入(stdin),它是没有定义的。但是有些编译器也定义了 fflush(stdin )的实现,比如微软的VC。其它编译器是否也定义了 fflush( stdin)的实现应当查找它的手册。GCC编译器没有定义它的实现,所以不能使用 fflush( stdin )来刷新输入缓存。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值