C++ 中的控制台暂停?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4343774/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:10:49  来源:igfitidea点击:

Console pause in C++?

c++windowsconsole

提问by RCIX

In C# you can cause the console to wait for a character to be input (which is useful for being able to see the last outputs of a console before the program exits). As a beginner in C++, i'm not sure what the equivalent is. Is there one?

在 C# 中,您可以使控制台等待输入字符(这对于能够在程序退出之前查看控制台的最后输出很有用)。作为 C++ 的初学者,我不确定等价物是什么。有吗?

回答by reko_t

The simplest way is simply:

最简单的方法很简单:

std::cin.get();

You can print something like "Press any key to continue..." before that. Some people will tell you about

您可以在此之前打印诸如“按任意键继续...”之类的内容。有些人会告诉你

system("pause");

But don't use it. It's not portable.

但不要使用它。它不便携。

回答by Mephane

#include <stdio.h>
// ...
getchar();

The function waits for a single keypress and returns its (integer) value.

该函数等待单个按键并返回其(整数)值。

For example, I have a function that does the same as System("pause"), but without requiring that "pause.exe" (which is a potential security whole, btw):

例如,我有一个功能与 相同System("pause"),但不需要“pause.exe”(这是一个潜在的安全整体,顺便说一句):

void pause()
{
  std::cout << std::endl << "Press any key to continue...";
  getchar();
}

回答by Ignacio Vazquez-Abrams

There is nothing in the standard, and nothing cross-platform. The usual method is to wait for <Enter> to be pressed, then discard the result.

标准中没有任何内容,也没有跨平台的内容。通常的方法是等待 <Enter> 被按下,然后丢弃结果。

回答by adrian

The incorrect solution would be to use system("pause")as this creates security holes (malicious pause.exe in directory!) and is not cross-platform (pause only exists on Windows/DOS).

不正确的解决方案是使用,system("pause")因为这会产生安全漏洞(目录中的恶意 pause.exe!)并且不是跨平台的(暂停仅存在于 Windows/DOS 上)。

There is a simpler solution:

有一个更简单的解决方案:

void myPause() {
    printf("Press any key to continue . . .");
    getchar();
}

This uses getchar(), which is POSIX compliant (see this). You can use this function like this:

这使用getchar(),这是符合 POSIX 的(请参阅)。你可以像这样使用这个函数:

int main() {
    ...
    myPause();
}

This effectively prevents the console from flashing and then exiting.

这有效地防止了控制台闪烁然后退出。