Problems with error check

i'm having problems with the error control, can't figure out why it doesnt stop, and sorry for poor english

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
48
  #include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int n, m, sumR, sumB, xnum, max, min, i, x, numR, numB ;
    bool fail;
    float  mediaR;
    cout << "insert the value of 'n': ";
    cin >> n;
    max=n;
    min=n;
    cout << "insert the value of 'm': "; 
    cin >> m;
    if (m>max){
       max=m;
    }
    if (m<min){            
       min=m;
    }
    numR=0;
    sumR=0;
    xnum=0;
    while (numR!=100)
          {
           cout << "insert a number (to terminate insert 100): ";
           cin >> numR;
           if (!isdigit(numR)){
              //fail=cin.fail();          //from here
              //cin.clear();
              //fail=true;               // causing problems
              //cin.ignore(numeric_limits<streamsize>::max(), '\n'); // to here
              cout<< "that's not a numeric value\n";
              numR=0;
           continue;}
           else
           if (numR==100){
             cout << "the numbers ended\n";
             break;
             }
           else { 
           sumR+=numR;
           xnum++;
           if (numR==100 && xnum==0){
              cout << "no value inserted\n";}
           }    
Last edited on
Instead of testing with idigit() you should be testing the stream state. When you try to insert an illegal value the stream will fail.
1
2
3
4
5
6
cin >> numR;
if(!cin)
{
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
...


isdigit() tests a character not an integer. It tests for an ASCII representation of a digit. Your program does ever read a numerical value in the range of INT_MIN..INT_MAX, so line 30..38 are obsolete.
Topic archived. No new replies allowed.