[c] How to pause in C?

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?

This question is related to c

The answer is


For Linux; getchar() is all you need.

If you are on Windows, check out the following, it is exactly what you need!

kbit() function

  • kbhit() function is used to determine if a key has been pressed or not.
  • To use kbhit() in C or C++ prorams you have to include the header file "conio.h".

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.


Good job I remembered about DOS Batch files. Don't need Getchar() at all. Just write the batch file to change directory (cd) to the folder where the program resides. type the name of the exe program and on the next line type pause. example:

cd\

wallpaper_calculator.exe 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.


I assume you are on Windows. Instead of trying to run your program by double clicking on it's icon or clicking a button in your IDE, open up a command prompt, cd to the directory your program is in, and run it by typing its name on the command line.


If you want to just delay the closing of the window without having to actually press a button (getchar() method), you can simply use the sleep() method; it takes the amount of seconds you want to sleep as an argument.

#include <unistd.h>
// your code here
sleep(3); // sleep for 3 seconds

References: sleep() manual


You could also just use system("pause");


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.


getch() can also be used which is defined in conio.h.

The sample program would look like this :

#include <stdio.h>
#include <conio.h>

int main()
{
    //your code 
    getch();
    return 0; 
} 

getch() waits for any character input from the keyboard (not necessarily enter key).


If you are making a console window program, you can use system("pause");