setbuf函数使用注意事项

 

setbuf函数使用注意事项

分类: c   85人阅读  评论(0)  收藏  举报
C

程序输出有两种方式:一种是即时处理方式,另一种是先暂存起来,然后再大块写入的方式,前者往往造成较高的系统负担。因此,c语言实现通常都允许程序员进行实际的写操作之前控制产生的输出数据量。

这种控制能力一般是通过库函数setbuf实现的。如果buf是一个大小适当的字符数组,那么:

setbuf(stdout,buf);

语句将通知输入/输出库,所有写入到stdout的输出都应该使用buf作为输出缓冲区,直到buf缓冲区被填满或者程序员直接调用fflush(译注:对于由写操作打开的文件,调用fflush将导致输出缓冲区的内容被实际地写入该文件),buf缓冲区中的内容才实际写入到stdout中。缓冲区的大小由系统头文件<stdio.h>中的BUFSIZ定义

举例说明如下(代码通过VS2008编译)


#include <iostream>
#include<fstream>

int main(int argc, char* argv[])
{
    char* outbuf =  new char [100];
    setbuf(stdout,outbuf);//将输出流绑定到outbuf上
    puts("helloworld\n");//内容输入到outbuf内
    //setbuf(stdout,NULL);//如果启用这行代码,输出流恢复原来的状态,puts输出到控制台
    delete[] outbuf;
    system("pause");
    return 0;

}


 

ungetc()函数的用法

分类: c   89人阅读  评论(0)  收藏  举报

ungetc函数是将输出流中的废弃数据退入流中去。

MSDN是这样定义的

int ungetc(
   int c,
      FILE *stream 
);
Parameters
c Character to be pushed.
stream Pointer to FILE structure.
Return Value
If successful, each of these functions returns the character argument c. If c cannot be pushed back or if no character has been read, the input stream is unchanged and ungetc returns EOF; ungetwc returns WEOF. If stream is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue,EOF or WEOF is returned and errno is set to EINVAL.


贴出实例代码:代码通过VS2008编译
/*************************************************************/
#include <iostream>
//#pragma  pack(4)
#include <cctype>




int main(int argc,char *argv[])
{
    int ch=0,sum=0;
    while ( ( ch=getchar() )!=EOF&&isdigit(ch) )
    {
        sum*=10;
        ch-='0';
        sum+=ch;
    }
    ungetc(ch,stdin);
    printf("%d\n",sum);
    fflush(stdin);
    system("pause");
    return 0;
}
/*******************************************************************/
输入:12345r
输出:12345

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值