Preventing console window from closing on Visual Studio C/C++ Console application

前端 未结 21 1658
灰色年华
灰色年华 2020-11-21 23:42

This is a probably an embarasing question as no doubt the answer is blindingly obvious.

I\'ve used Visual Studio for years, but this is the first time I\'ve done any

相关标签:
21条回答
  • 2020-11-22 00:07

    A somewhat better solution:

    atexit([] { system("PAUSE"); });
    

    at the beginning of your program.

    Pros:

    • can use std::exit()
    • can have multiple returns from main
    • you can run your program under the debugger
    • IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)

    Cons:

    • have to modify code
    • won't pause on std::terminate()
    • will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:

    extern "C" int __stdcall IsDebuggerPresent(void);
    int main(int argc, char** argv) {
        if (IsDebuggerPresent())
            atexit([] {system("PAUSE"); });
        ...
    }
    
    0 讨论(0)
  • 2020-11-22 00:08

    add “| pause” in command arguments box under debugging section at project properties.

    0 讨论(0)
  • 2020-11-22 00:08

    Go to Setting>Debug>Un-check close on end.

    0 讨论(0)
  • 2020-11-22 00:10

    try to call getchar() right before main() returns.

    0 讨论(0)
  • 2020-11-22 00:14

    Here is a way for C/C++:

    #include <stdlib.h>
    
    #ifdef _WIN32
        #define WINPAUSE system("pause")
    #endif
    

    Put this at the top of your program, and IF it is on a Windows system (#ifdef _WIN32), then it will create a macro called WINPAUSE. Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.

    0 讨论(0)
  • 2020-11-22 00:15

    Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:

    1. The debug window retains the contents of the WSL shell window that closed.

    2. The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.

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