Keep Console Open

This is what I'm trying to do: http://www.cplusplus.com/forum/beginner/1988/#msg7682
However it is not working with exceptions
All in one ( issues with exit too )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class keep_open{
public:
	~keep_open(){
		std::cout << "Press Enter to end ";
		std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n');
	}
};

int main(){
	keep_open dummy;
	//exit(1);
	throw 42;
	cout << "hello world" << endl;	
	return 0;
}


However, I would like that the original code will be untouched
1
2
3
4
5
6
7
//main.cpp
#include <iostream>

int main(){
	std::cout << "hello world" << std::endl;	
	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
//keep_it_open.h
#ifndef KEEP_IT_OPEN_H
#define KEEP_IT_OPEN_H

class keep_open{
public:
	~keep_open();
};

extern keep_open KeepOpen; //I'm not sure if this is the correct way for creating the object
#endif 
1
2
3
4
5
6
7
8
9
10
11
//keep_it_open.cpp
#include "keep_it_open.h"
#include <iostream>
#include <limits>

keep_open::~keep_open(){
	std::cout << "Press Enter to end ";
	std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n');
}

keep_open KeepOpen;

This way if I want the "release" version I just compile main.cpp
But g++ *.cpp will keep the console open. (it works with exit, but fail with exceptions)
It seems that exit only calls the destructor of global variables.

Edit: http://stackoverflow.com/questions/222175/why-destructor-is-not-called-on-exception
If no matching handler is found in a program, the function terminate() (_except.terminate_) is called. Whether or not the stack is unwound before calling terminate() is implementation-defined.
Damn.
Last edited on
Hmm, I didn't know that. Might the following fix the problem?

1
2
3
4
5
6
7
8
int main() {
	try {

		std::cout << "hello world" << std::endl;

	} catch (...) { throw; }
	return 0;
}
Yes, but the code will be dirtied.
main.cpp will need to #include "keep_it_open.h" , and the object must be created inside the try block, (and you need the try/catch)
this is what i use

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

class pause
{
public:
	~pause()
	{
		 cout << endl << endl;
		 cout << "Press ENTER to exit...";
		 cin.ignore( numeric_limits<streamsize>::max(), '\n' );
	}
};


int main(int argc, char* argv[])
{
    
        // do something

	pause ps;
	return 0;
}
That's what I'm trying to do. But the idea was that the program to be tested will be as clean as possible, so I could pass from the test to the release with minimal change.
In this case
g++ main.cpp keep_it_open.cpp -o test.bin
g++ main.cpp -o release.bin


Because of there is no guarantee that the destructor to be called in case of exception, segmentation fault, abort, I guess I will take another approach.
Like http://www.cplusplus.com/forum/beginner/1988/page3.html#msg14102 (but for linux)
Last edited on
Topic archived. No new replies allowed.