cerr/exit(1) How to?

How to properly use cerr and exit(int).

For instance, using an if else statment, say the else is exit(1). How to tell the compiler to write that 1 to a file so I can see the error code?

and cerr for output errors, How is this used properly?

IE:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using std::cout;
using std::cin;

int main()
{
	int num1 = 0;
	
	cout << "\n\nEnter a number: "
	cin >> num1;
	
	if (cin.good())
	    cout << num1;
	else
		exit(1);
		
	return 0;
}

OR:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using std::cout;
using std::cin;
using std::cerr;

int main()
{
	int num1 = 0;
	
	cout << "\n\nEnter a number: "
	cin >> num1;
	
	if (cin.good())
	{
		cout << num1;
                }
	else
	{
		cerr << "\n\n.......INVALID INPUT\n....Exiting...\n\n";
		exit(1);
	}
	return 0;
}

Thanks in advance!
Last edited on
Under Linux, at the command prompt type
echo $?

Under Windows at the command prompt type
echo %errorlevel%
Thanks for the help. So lets say im in windows, and I compile a program and it ends up executing exit(1).

//If i type echo %errorlevel%, does that mean the command line should be in the same directory as my cpp file?

edit: nm I figured it out.

Is there a way to have all cerr output logged to a txt file?
Last edited on
Under Linux it's easy from the command line:
myprog 2> errorfile.txt

In Windows, I'm not so sure. myprog > errorfile.txt will sort of work, but Windows doesn't make the same sort of differentiation between stdout and stderr as Linux. You'll probably have to redirect stderr to a file.

You can use freopen to redirect stderr to a file, here's how to use it:
http://www.cplusplus.com/reference/clibrary/cstdio/freopen/
Topic archived. No new replies allowed.