How do I prevent my program from closing immediately after running?

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 2K views
LasTSurvivoR
Messages
16
Reaction score
0
I wrote my code and try to setup the program , desperately the program closes it so quickly return 0 or getch() commands doesn't work how can I prevent it with a code ?
 
Physics news on Phys.org
ı mean the ms dos windows disappears so quickly..
 
Yes if you execute the program from within windows the DOS window closes when the program ends. You could just open a DOS window and then execute the program from the command line, that way the DOS window will stay open.

When characters are pressed they are placed in a buffer, and getch() will return the oldest character from the buffer, but if there is nothing in the buffer it will return ERR, I think (it depends on certain settings). But anyway you can use getchar(), that should work. It will wait until return is pressed.

You could put something like this at the end of your program:
Code:
printf("\npress q to quit\n");
do
{
  key = getchar();
} while (key != 'q');
or
Code:
printf("\npress q to quit\n");
do
{
  key = getch();
} while (key != 'q');
 
you can just put

getch()
or scanf()
to pause the prpogramme...
else do a loop from 1...n and display something.
 
in windows i use system("pause"); to prevent the window from disappearing. I don't really know if that is good way though.
 
This problem arises in a few compilers. I guess you are not using Visual C++ because if you are using Visual C++, it automatically takes care of this issue.

As others suggested you can simply use;

getchar();
getch();
system("PAUSE");