Stream应用注意点

  1.  

1. Stream 的类层次

2. Stream 的状态 (iostate) /IO 格式化flag (fmtflags) / 文件打开模式(openmode) / 文件定位标记 (seekdir) 。

3. Stream 中failbit 和 badbit 的差别。failbit 用于读取时格式不符的情况。注意,在格式不符时,stream会跳过不符的输入并且不对变量进行更改。

4. Stream 中 ignore()/peek()/unget() 的使用

5. 重定向标准输入/输出的能力。

  std::ofstream file ("cout.txt");
  std::cout.rdbuf (file.rdbuf());
6. 在类继承中如何正确使用 operator << ,operator >> 

class Fraction {
  ...
  public:
  virtual void printOn (std::ostream& strm) const; // output
  virtual void scanFrom (std::istream& strm); // input
  ...
  };

  std::ostream& operator << (std::ostream& strm, const Fraction& f)
  {
  f.printOn (strm);
  return strm;
  }

  std::istream& operator >> (std::istream& strm, Fraction& f)
  {
  f.scanFrom (strm);
  return strm;
  }

7. 用户定义的标志 和 用户注册的回调函数

ios_base::xalloc();/ ios_base::iword() / ios_base::pword();

  namespace std {
  class ios_base {
  public:
  // kinds of callback events
  enum event { erase_event, imbue_event, copyfmt_event };
  // type of callbacks
  typedef void (*event_callback) (event e, ios_base& strm,
  int arg);
  // function to register callbacks
  void register_callback (event_callback cb, int arg);
  ...
  };
  }

8. Manipulators

具体看以下在标准c++库中的例子:

8。1 变量类型

  template<typename _CharT, typename _Traits>
  basic_istream<_CharT, _Traits>& 
  basic_istream<_CharT, _Traits>::
  operator>>(float& __n)
8。2 函数类型

  template<typename _CharT, typename _Traits>
  basic_istream<_CharT, _Traits>& 
  basic_istream<_CharT, _Traits>::
  operator>>(__ios_type& (*__pf)(__ios_type&))
  {
  __pf(*this);
  return *this;
  }
8。3 带参数函数的间接支持

  struct _Setiosflags { ios_base::fmtflags _M_mask; };

  inline _Setiosflags 
  setiosflags(ios_base::fmtflags __mask)  // 返回结构的带参数函数
  { 
  _Setiosflags __x; 
  __x._M_mask = __mask; 
  return __x; 
  }

  template<typename _CharT, typename _Traits>
  inline basic_istream<_CharT,_Traits>& 
  operator>>(basic_istream<_CharT,_Traits>& __is, _Setiosflags __f)  //结构
  { 
  __is.setf(__f._M_mask); 
  return __is; 
  }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值