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

前端 未结 21 1966
灰色年华
灰色年华 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"); });
        ...
    }
    

提交回复
热议问题