C++的tie()函数

今天看C ++ primer 时,看到了ios::tie() 函数。不明白其含义,跟不知道作用。于是上网查了一下。

cplusplus.com 给出的定义是:

ostream* tie ( ) const; //返回指向绑定的输出流的指针。
ostream* tie ( ostream* tiestr ); //将tiestr指向的输出流绑定到该对象上,并返回一个绑定的输出流指针。
什么意思呢?

就是说对于一个ios(输入输出流)对象,可以把一个输出流和它“绑定”起来。不带参数执行,返回“绑定”的输出流指针;带一个输出流指针作为参数,则重新设置绑定的对象,并返回前任绑定对象(指针)。

但是,什么是“绑定”呢?

比方说,对于下面这个程序:
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream ofs;
  ofs.open ("test.txt");

  cin.tie (&ofs); //注释掉这一行试试看
  *cin.tie() << "There will be some text:";
  char c;
  while(cin >> c){
    ofs << c;
  }

  ofs.close();

  return 0;
}

用linux下watch命令(windows下还不知道有没有什么类似的东西,如果没有就用本办法:手动关掉再打开)实时察看test.txt文件,会发现每当你在终端里敲几个字后按下回车,test.txt文件里的文字就多了几个。
而如果你将代码中标注的那一行注释掉,就会发现,test.txt只有在程序运行结束(linux下按ctrl+d,windows下是ctrl+z结束输入)后才会有东西出现。
这就是“绑定”的效果,每当被“绑定”的对象有出入或输出操作,就会自动刷新“绑定”的对象的缓冲区,以达到实时的效果。

 

Remarks

tie causes two streams to be synchronized, such that, operations on one stream occur after operations on the other stream are complete.

Example

In this example, by tying cin to cout, it is guaranteed that the "Enter a number:" string will go to the console before the number itself is extracted from cin. This eliminates the possibility that the "Enter a number:" string is still sitting in the buffer when the number is read, so that we are certain that the user actually has some prompt to respond to. By default, cin and cout are tied.

#include <ios>
#include <iostream>

int main( ) 
{
   using namespace std;
   int i;
   cin.tie( &cout );
   cout << "Enter a number:";
   cin >> i;
}
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值