How to pause in C?

后端 未结 10 844
清歌不尽
清歌不尽 2020-12-05 18:11

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?

相关标签:
10条回答
  • 2020-12-05 18:58

    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.

    0 讨论(0)
  • 2020-12-05 18:59

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

    0 讨论(0)
  • 2020-12-05 19:04

    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.

    0 讨论(0)
  • 2020-12-05 19:06

    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.

    0 讨论(0)
提交回复
热议问题