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