C++ - 保持控制台窗口打开?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1908512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ - Hold the console window open?
提问by Alex
My question is super simple, but I'm transitioning from C# to C++, and I was wondering what command holds the console window open in C++?
我的问题非常简单,但我正在从 C# 过渡到 C++,我想知道什么命令可以在 C++ 中打开控制台窗口?
I know in C#, the most basic way is:
我知道在 C# 中,最基本的方法是:
Console.ReadLine();
Or if you want to let the user press any key, its:
或者如果你想让用户按任意键,它的:
Console.ReadKey(true);
How do you do this in C++? The only reason I ask this simple of a question here, is that I haven't been able to find a good and clear answer out there on the internet.
你如何在 C++ 中做到这一点?我在这里问这个简单的问题的唯一原因是我无法在互联网上找到一个好的和明确的答案。
回答by Cogwheel
How about std::cin.get();
?
怎么样std::cin.get();
?
Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main()
.
此外,如果您使用的是 Visual Studio,则无需调试即可运行(默认情况下为 CTRL-F5),并且最终不会关闭控制台。如果你用调试运行它,你总是可以在main()
.
回答by Mike Weller
The right way
正确的方式
cin.get();
cin.get()
is C++ compliant, and portable. It will retrieve the next character from the standard input (stdin). The user can press enter and your program will then continue to execute, or terminate in our case.
cin.get()
符合 C++,可移植。它将从标准输入 (stdin) 中检索下一个字符。用户可以按回车键,然后您的程序将继续执行,或者在我们的情况下终止。
Microsoft's take
微软采取
Microsoft has a Knowledge Base Article titled Preventing the Console Window from Disappearing. It describes how to pause execution only when necessary, i.e. only when the user has spawned a new console window by executing the program from explorer. The code is in C which I've reproduced here:
Microsoft 有一篇名为“防止控制台窗口消失”的知识库文章。它描述了如何仅在必要时暂停执行,即仅当用户通过从资源管理器执行程序生成新的控制台窗口时。代码在 C 中,我在这里复制:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
CONSOLE_SCREEN_BUFFER_INFO csbi;
HANDLE hStdOutput;
BOOL bUsePause;
void main(void)
{
hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleScreenBufferInfo(hStdOutput, &csbi))
{
printf("GetConsoleScreenBufferInfo failed: %d\n", GetLastError());
return;
}
// if cursor position is (0,0) then use pause
bUsePause = ((!csbi.dwCursorPosition.X) &&
(!csbi.dwCursorPosition.Y));
printf("Interesting information to read.\n");
printf("More interesting information to read.\n");
// only pause if running in separate console window.
if (bUsePause)
{
int ch;
printf("\n\tPress any key to exit...\n");
ch = getch();
}
}
I've used this myself and it's a nice way to do it, under windows only of course. Note also you can achieve this non-programatically under windows by launching your program with this command:
我自己使用过这个,这是一个很好的方法,当然只在 Windows 下。另请注意,您可以通过使用以下命令启动您的程序,在 Windows 下以非编程方式实现此目的:
cmd /K consoleapp.exe
The wrong way
错误的方法
Do not use any of the following to achieve this:
请勿使用以下任何方法来实现此目的:
system("PAUSE");
This will execute the windows command 'pause' by spawning a new cmd.exe/command.com process within your program. This is both completely unnecessary and also non-portable since the pause command is windows-specific. Unfortunately I've seen this a lot.
这将通过在您的程序中生成一个新的 cmd.exe/command.com 进程来执行 windows 命令“暂停”。这是完全没有必要的,也是不可移植的,因为 pause 命令是特定于 Windows 的。不幸的是,我已经看到了很多。
getch();
This is not a part of the C/C++ standard library. It is just a compiler extension and some compilers won't support it.
这不是 C/C++ 标准库的一部分。它只是一个编译器扩展,有些编译器不支持它。
回答by jfseb
If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.
如果您的问题是在 Visual Studio 中保留控制台窗口而不修改您的应用程序(c 代码)并使用 Ctrl+F5 运行它(运行 Ctrl+F5 时)但窗口仍在关闭,则主要提示是设置 /SUBSYSTEM Visual Studio 项目中的 :CONSOLE 链接器选项。
as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6
正如 DJMooreTX 在http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6 中所解释的
1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.
1) 打开您的项目,然后转到解决方案资源管理器。如果您在 K&R 中跟随我,您的“解决方案”将是“你好”,下面有 1 个项目,还有“你好”以粗体显示。
Right click on the 'hello" (or whatever your project name is.)
Choose "Properties" from the context menu.
Choose Configuration Properties>Linker>System.
For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.
Choose "Console (/SUBSYSTEM:CONSOLE)"
Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)
右键单击“你好”(或任何您的项目名称。)
从上下文菜单中选择“属性”。
选择配置属性>链接器>系统。
对于右侧窗格中的“子系统”属性,单击右侧列中的下拉框。
选择“控制台(/SUBSYSTEM:CONSOLE)”
单击应用,等待它完成它所做的一切,然后单击确定。(如果“应用”显示为灰色,请选择其他子系统选项,单击“应用”,然后返回并应用控制台选项。我的经验是 OK 本身不起作用。)
Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.
现在执行 Boris 的 CTRL-F5,等待您的程序编译和链接,在桌面上所有其他垃圾下找到控制台窗口,然后阅读您的程序输出,然后是心爱的“按任意键继续.... “ 迅速的。
Again, CTRL-F5 and the subsystem hints work together; they are not separate options.
同样,CTRL-F5 和子系统提示一起工作;它们不是单独的选项。
回答by Thomas Matthews
A more appropriate method is to use std::cin.ignore
:
更合适的方法是使用std::cin.ignore
:
#include <iostream>
void Pause()
{
std::cout << "Press Enter to continue...";
std::cout.flush();
std::cin.ignore(10000, '\n');
return;
}
回答by Daver
You can also lean on the IDE a little. If you run the program using the "Start without debugging" command (Ctrl+F5 for me), the console window will stay open even after the program ends with a "Press any key to continue . . ." message.
您也可以稍微依赖 IDE。如果您使用“启动而不调试”命令(对我来说是 Ctrl+F5)运行程序,即使程序以“按任意键继续...”结束后,控制台窗口仍将保持打开状态。信息。
Of course, if want to use the "Hit any key" to keep your program running (i.e. keep a thread alive), this won't work. And it does not work when you run "with debugging". But then you can use break points to hold the window open.
当然,如果想使用“Hit any key”来保持程序运行(即保持线程活动),这是行不通的。当您运行“带调试”时它不起作用。但是你可以使用断点来保持窗口打开。
回答by DanDan
In windows, you can use _getch()
in the
在 Windows 中,您可以_getch()
在
<conio.h>
header.
标题。
回答by isu3ru
I use std::getwchar()
in my environment which is with mingw32 - gcc-4.6.2 compiler, Here is a sample code.
我std::getwchar()
在我的环境中使用了 mingw32 - gcc-4.6.2 编译器,这是一个示例代码。
#include <iostream>
#include "Arithmetics.h"
using namespace std;
int main() {
ARITHMETICS_H::testPriorities();
cout << "Press any key to exit." << endl;
getwchar();
return 0;
}
回答by S. Paris
As Thomas says, the cin ignore is a good way. To always wait for user to press enter (even if exit is used), register a function atexit:
正如托马斯所说,cin ignore 是一个好方法。要始终等待用户按 Enter(即使使用了 exit),请注册一个函数 atexit:
#include <iostream>
void pause()
{ ::std::cout<<"\nPress ENTER to exit.";
::std::cin.sync();
if(::std::cin.get()!='\n')
::std::cin.ignore(0xFFFFFFFF,'\n');
}
int main()
{
atexit(pause);
// whatever
return 0;
}
回答by ufukgun
if you create a console application, console will stay opened until you close the application.
如果您创建控制台应用程序,控制台将保持打开状态,直到您关闭该应用程序。
if you already creat an application and you dont know how to open a console, you can change the subsystem as Console(/Subsystem:Console) in project configurations -> linker -> system.
如果您已经创建了一个应用程序并且您不知道如何打开控制台,您可以在项目配置->链接器->系统中将子系统更改为Console(/Subsystem:Console)。
回答by Jerry Coffin
Roughly the same kinds of things you've done in C#. Calling getch()
is probably the simplest.
与您在 C# 中所做的事情大致相同。调用getch()
可能是最简单的。