C++入门记录之处理失败的输入流

在代买编写的过程中多少会出现输入值与变量类型不符合的情况这样直接导致代码的错误结束。则有通过bool类型的的函数cin.file();来判断输入流是否正常,若不正常则通过新的输出流cerr——标准错误输出流,与cout几乎相同,出现在同一个界面或窗口,只是使用的场合不同而已。

 1 #include<iostream>
 2 using namespace std;
 3 int main( int argc , char * argv[])
 4 {
 5     int ReturnCode = 0;
 6     float Dividend = 0;
 7 cout<< "Dividend:";
 8 cin>>Divedend;
 9 if(!cin.file())    
10 {
11   float Divisor =1 ;
12   cout<<"Divisor:";
13   cin>>Divisor;
14     if(!cin.file())
15     {
16       float Resault = (Divedend/Devisor);
17       cout<<Result<<endl;
18 
19     }
20     else 
21     {
22       cerr<<"Input error ,not a number?"<<endl;
23       cin.clear();                    //清除输入流
24       char BadInput[5];                  //用来存放等待的字符串
25       cin>>BadInput;
26       ReturnCode = 1;
27 
28      };
29     }
30 else 
31 { 
32 cerr<<"Input error ,not a number?"<<endl;
33     cin.clear();
34     char BadInput[5];
35     cin>>BadInput;
36     ReturnCode = 1;
37 
38 }
39 char StopCharacter;
40 cout<<endl<<"press a Key and \"Enter"\: ";
41 cin >>StopChareter;
42 return ReturnCode;
43 }

 

转载于:https://www.cnblogs.com/miaorn/p/11557401.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值