cin读取出错的解决方案

(1)
include<iostream.h>
#include<stdlib.h>
void main()
 {
  int choice;
  cout<<"choice:";
  cin>>choice;
  while(!cin)
  {
   cerr<<"Invalid character"<<endl<<"Enter again-choice:";
   cin.clear();
   int chars_to_skip=cin.rdbuf()->in_avail();
   cin.ignore(chars_to_skip);
   cin>>choice;
  }
  system("cls");
}


(2)写成函数,进行调用

#include<iostream.h>
#include<stdlib.h>
istream& Flush(istream& stream)
 {
  stream.clear();
  int chars_to_skip=stream.rdbuf()->in_avail();
  return stream.ignore(chars_to_skip);
 }
void main()
 {
  int choice;
  cout<<"choice:";
  cin>>choice;
  while(!cin)
  {
   cerr<<"Invalid character"<<endl<<"Enter again-choice:";
   Flush(cin);
   cin>>choice;
  }
  system("cls");
}


 

 cin.rdbuf()->in_avail()函数

rdbuff() is a method to access the streambuf* member of  cin  which is a  istream object. 

 You havent read anything in yet so in_avail()  returns zero when you call it.

If cin's streambuf is empty sb->in_avail() will return 0.

If cin's streambuf is empty  sb->in_avail() will return the number of readed last time.

#include<iostream.h>
#include<stdlib.h>
void main()
 {
    int a;
    streambuf* sb;
    sb = cin.rdbuf();
    cout<<sb->in_avail()<<endl; // will print zero
    cin>>a;
    sb = cin.rdbuf();
    cout<<sb->in_avail()<<endl; // will print 输入的个数 

}


 C++中rdbuf重定向流的使用

#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{std::ifstream log("out.log");
 std::streambuf * x=cout.rdbuf(log.rdbuf());// 返回cout的流对象指针,使cout重定向到log文件中
 std::cout << "Testn";// 写入到文件中
 std::cout.rdbuf(x);// 恢复cout的流对象指针
 std::cout << "Test2n";// 写入cout
 return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值