//flex table opened by JP

Click to See Complete Forum and Search --> : Quick C++ question


nothing
01-11-2004, 12:00 PM
Why do I have to use cerr instead of cout when displaying an error message after trying to open a file?

fishybawb
01-11-2004, 01:46 PM
I don't know...

This works OK:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream fileHandle;

fileHandle.open("test.txt");

if(fileHandle == NULL)
cout << "Error opening file" << endl;
else
{
cout << "File opened OK!" << endl;
fileHandle.close();
}

return 0;
}

Or are you trying to do something different?

nothing
01-11-2004, 02:32 PM
That is basically what I am trying to do, just slightly different. Instead of doing it like this

ifstream fileHandle;

fileHandle.open("test.txt");

if(fileHandle == NULL)
cout << "Error opening file" << endl;


I'm doing it like this

ifstream fileHandle ("test.txt", ios::in);

if (!hours_file_write) {

cerr << "Error opening file" << endl;


which seems to be the same thing right? I just can't find in my book why they use cerr instead of cout :rolleyes:

fishybawb
01-11-2004, 02:46 PM
Yeah, that's the same thing really. cerr's unbuffered whereas cout's buffered (stores it in a buffer, then outputs it). cerr's like the old C stderr, where you could define a different device (monitor/printer/ file etc) to print errors to, distinguishing that output from normal program output.

nothing
01-11-2004, 03:37 PM
So, which one should I use when displaying error messages? :D

fishybawb
01-11-2004, 03:45 PM
Whatever the hell you like, I'd say :p :D
Back in the days when console-style programming was all there was, I often found it useful to keep an error log file open and output all the errors to that - stops error messages from clogging up everything else then, and pretty handy for debugging messages (variable contents etc) too.