input exception try/catch

Mar 16, 2014 at 10:47pm
I am trying to throw an input error exception when a char is input into an int variable but when i test it with ft=a the program runs some kind of infinite loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
int main()
{
   char error='a';
   double ft;
   double in;
   double cm;
   int again=0;
   char yn;
   while(again<=0)
   {
      try{
         cout<<"feet: ";
         cin>>ft;
         if(!cin)
            throw error;
         cout<<"inches: ";
         cin>>in;
         if(!cin)
            throw error;
         cout<<"centimeters: ";
         if(ft<0)
            throw -1;
         if(in<0)
            throw -1;
         cm=(12*ft*2.54)+(in*2.54);
         cout<<cm<<endl;
      }
      catch(int)
      {
         cout<<"Error values must be positive."<<endl;
         cout<<"enter new values? y/n"<<endl;
         cin>>yn;
         if(yn=='n')
            again=1;
      }
      catch(...)
      {
         cout<<"Error values must be numeric.";
         cout<<"enter new values? y/n"<<endl;
         cin>>yn;
         if(yn=='n')
            again=1;
      }
   }
system ("PAUSE");
return 0;
}
Mar 16, 2014 at 10:59pm
You never clear cin's error flags, so the input on line 40 will fail, so again doesn't get set to anything, so the loop will run again (with the input continuing to fail).
Mar 16, 2014 at 11:10pm
how do i fix that?
Mar 16, 2014 at 11:28pm
36
37
38
39
40
41
42
43
44
45
46
catch(...)
{
    cin.clear(); // Clear error flags
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Clear out the input buffer
    
    cout<<"Error values must be numeric.";
    cout<<"enter new values? y/n"<<endl;
    cin>>yn;
    if(yn=='n')
        again=1;
}

You'll need to #include <limits> as well.
Mar 16, 2014 at 11:38pm
thank you
Topic archived. No new replies allowed.