Preventing console window from closing on Visual S

2018-12-31 04:44发布

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 'Console Application' development.

When I run my application the console window pops up, the program output appears and then the window closes as the application exits.

Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?

18条回答
闭嘴吧你
2楼-- · 2018-12-31 05:07

You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

and this way the window would not close until you enter data for the a variable.

查看更多
回忆,回不去的记忆
3楼-- · 2018-12-31 05:08

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.

查看更多
余欢
4楼-- · 2018-12-31 05:11

Right click on your project

Properties>Configuration Properties> Linker> System

select Console (/SUBSYSTEM:CONSOLE) in SubSystem option.

Now try it...it should work

查看更多
与君花间醉酒
5楼-- · 2018-12-31 05:11

If you're using .NET, put Console.ReadLine() before the end of the program.

It will wait for <ENTER>.

查看更多
无与为乐者.
6楼-- · 2018-12-31 05:12

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"); });
    ...
}
查看更多
谁念西风独自凉
7楼-- · 2018-12-31 05:13

Visual Studio 2015, with imports. Because I hate when code examples don't give the needed imports.

#include <iostream>;

int main()
{
    getchar();
    return 0;
}
查看更多
登录 后发表回答