How to pause in C?

183,487

Solution 1

you can put

getchar();

before the return from the main function. That will wait for a character input before exiting the program.

Alternatively you could run your program from a command line and the output would be visible.

Solution 2

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

Solution 3

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.

Solution 4

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.

Solution 5

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

Share:
183,487

Related videos on Youtube

CathyLu
Author by

CathyLu

Updated on July 09, 2022

Comments

  • CathyLu
    CathyLu 6 months

    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?

  • Michael K
    Michael K almost 12 years
    Yes, then you just press any key to finish the program and close the window.
  • John Bode
    John Bode almost 12 years
    +1 for "run from the command line", which is a skill that is sorely lacking these days.
  • Gavin H
    Gavin H almost 12 years
    @John - agreed, especially if your program prints to the console, it would only make sense to run it from the command line.
  • David Callanan
    David Callanan almost 5 years
    @JerryJeremiah he said "windows". I think pause also works on Linux and Mac.
  • Samie Bencherif
    Samie Bencherif over 3 years
    It depends who you're distributing to. Would also be nice if you can detect the difference between a command line invocation vs double click and act accordingly.

Related