Preventing Program Closure with Code: Solutions & Tips

AI Thread Summary
To prevent a DOS window from closing immediately after a program execution in Windows, it is recommended to run the program from the command line instead of directly executing it from Windows. This allows the DOS window to remain open after the program ends. To keep the program running until a key is pressed, developers can use functions like getchar(), getch(), or system("pause"). Implementing a loop that waits for a specific key press, such as 'q', can also effectively pause the program. Some compilers, like Visual C++, automatically manage this issue, but for others, these methods are necessary to avoid the window disappearing too quickly.
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 ?
 
Computer science 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.
 
Running your program from within the command prompt would also fix this problem.
 
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");
 
Back
Top