Couple quickies....

Why would someone use cerr instead of cout? I saw it was error streams but wouldnt cout work fine?

also...

1
2
3
4
5
6
7
8
9
10
else
       {
            cerr << "Input error, not a number?" << endl;
            
            cin.clear(); //Reset bits
            char BadInput[5];
            cin >> BadInput;
            
            ReturnCode = 1;
       };


why does cin.clear() need to be there for the "cerr" command to execute, try commenting it out ill give you the full code...

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
using namespace std;

int main(int argc, char *argv[])
{
    int ReturnCode = 0;
    
    float Dividend = 1;
    cout << "Dividend: ";
    cin >> Dividend;
    
    if (!cin.fail())  //Is a number
    {
       float Divisor = 1;
       cout << "Divisor: ";
       cin >> Divisor;
       
       if (!cin.fail()) //Divisor is a number
       {
          float Result = (Dividend/Divisor);
          cout << Result << endl;
       }
       else //Divisor not a number
       {
            cerr << "Input error, not a number?" << endl;
            
            cin.clear(); //Reset bits
            char BadInput[5];
            cin >> BadInput;
            
            ReturnCode = 1;
       };
    }
    else // Dividend NOT number
    {
         cerr << "Input error, not a number?" << endl;
         
         cin.clear(); // Reset
         char BadInput[5];
         cin >> BadInput;
         
         ReturnCode = 1;
    }
    
    char StopCharacter;
    cout << endl << "Press a key and \"Enter\": ";
    cin >> StopCharacter;
    
    return ReturnCode;
}
      


any help is greatly appreciated for understanding :)
There are three standard streams: stdin, stdout, and stderr; for input, output, and errors respectively. In C++, they are accessed with cin, cout, and cerr.

The cin.clear(); has nothing to do with cerr. What it does is reset the input stream's status flags to "everything's ok" so that you can continue reading stuff from it. (As long as any of the badbit, failbit, or eofbit flags are set, you cannot read/write from a stream.)

[edit] cout is buffered, but cerr is not.
The code you posted clears the input stream, then reads the remainder of the bad input before returning.

Hope this helps.
Last edited on
And also std::clog, used for logging.
Topic archived. No new replies allowed.