if (!cin) ?

I was looking at this code and wanted to what is the reason for lines 35 - 39:

" if(!cin)
{
cin.clear();
cin.ignore(100, '\n');
}
"
I'm not quite sure what this is being used for. Can anyone explain what this is actually doing? Thanks!

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
49
50
51
52
53
54
55
56
57
58
59
60
#include <cstdlib>
#include <iostream>

using namespace std;

double getsales (double &);
void findhighest (double, double, double, double);

int main(int argc, char *argv[])
{
    double northeast = 0;
    double southeast = 0;
    double northwest = 0;
    double southwest = 0;
    
    cout << "Enter NorthEast sales: $" ;
    cout << getsales(northeast) << endl;
    cout << "Enter SouthEast sales: $"; 
    cout << getsales(southeast) << endl;
    cout << "Enter NorthWest sales: $";
    cout << getsales(northwest) << endl;
    cout << "Enter SouthWest sales: $";
    cout << getsales(southwest) << endl;
    
    findhighest(northeast, southeast, northwest, southwest);
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

double getsales (double & num)
{
    do
    {
        if(!cin)
        {
            cin.clear();
            cin.ignore(100, '\n');
        }
        
        cin >> num;
        cout << "Number entered: ";
        
        
    }while(!cin || num <= 0);
    return num;
}

void findhighest (double ne, double se, double nw, double sw) 
{
    double high = ne;
    if(se > high)
        high = se;
    if(nw > high)
        high = nw;
    if(sw > high)
        high = sw;
        
    cout << "the highest number is: " << high << endl;
}
It checks if anything has been inputted and not actually dumped into a character. This is usually done for when you... well, do things like character or number input and switch types. Otherwise, you can end up with it automatically fetching a response from the buffer and not letting you type.
closed account (SECMoG1T)
In addition to what ispil said it checks if an error state have been set on the stream . There error States can be set

1. failbit - it is set when what is described by ispil happens entering a
char for an integer etc.
2. eofbit - set when the stream strikes an end of file (eof) character.

3. badbit - is set when the stream runs into unrecoverable error such as corrupted data.

You can clear the first and second errors by using cin.clear () and can continue using the stream .
Makes sense now. Thanks y'all!
Topic archived. No new replies allowed.