I am a beginner of C. I run the C program, but the window closes too fast before I can see anything. How can I pause the window?
Under POSIX systems, the best solution seems to use:
#include <unistd.h>
pause ();
If the process receives a signal whose effect is to terminate it (typically by typing Ctrl+C in the terminal), then pause
will not return and the process will effectively be terminated by this signal. A more advanced usage is to use a signal-catching function, called when the corresponding signal is received, after which pause
returns, resuming the process.
Note: using getchar()
will not work is the standard input is redirected; hence this more general solution.
If you are making a console window program, you can use system("pause");
Is it a console program, running in Windows? If so, run it from a console you've already opened. i.e. run "cmd", then change to your directory that has the .exe in it (using the cd command), then type in the exe name. Your console window will stay open.
For Linux; getchar() is all you need.
If you are on Windows, check out the following, it is exactly what you need!
kbit() function
For example, see how it works in the following program;
//any_key.c
#include <stdio.h>
#include <conio.h>
int main(){
//code here
printf ("Press any key to continue . . .\n");
while (1) if (kbhit()) break;
//code here
return 0;
}
When I compile and run the program, this is what I see.
Only when user presses just one key from the keyboard, kbhit() returns 1.