在 C++ 程序中暂停控制台

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

Pause Console in C++ program

c++

提问by Destructor

Which is best way to pause the console in C++ programs?

在 C++ 程序中暂停控制台的最佳方法是什么?

  1. using cin.get()
  2. or using system("pause")
  3. or using C functions like getch()or getchar()?
  1. 使用 cin.get()
  2. 或使用 system("pause")
  3. 或使用 C 函数,如getch()getchar()

Is it true that use of system("pause")leads to non portable code and can't work in UNIX?

使用system("pause")会导致不可移植的代码并且不能在 UNIX 中工作是真的吗?

Is cin.get() is better to use to pause console?

cin.get() 更适合用来暂停控制台吗?

回答by Sebastian Mach

There might be a best way (like using the portable cin.get()), but a goodway doesn't exist. A program that has done its job should quit and give its resources back to the computer.

可能有最好的方法(比如使用便携式cin.get()),但不存在好的方法。完成其工作的程序应该退出并将其资源返回给计算机。

And yes, any usage of system()leads to unportable code, as the parameter is passed to the shell that owns your process.

是的,任何使用都会system()导致代码不可移植,因为参数会传递给拥有您的进程的 shell。

Having pausing-code in your source code sooner or later causes hassles:

在源代码中包含暂停代码迟早会导致麻烦:

  • someone forgets to delete the pausing code before checking in
    • now all working mates have to wonder why the app does not close anymore
    • version history is tainted
  • #defineis hell
  • it's annoying to anyone who runs your code from the console
  • it's very, very, very annoying when trying to start and end your program from within a script; quadly annoying if your program is part of a pipeline in the shell, because if the program does not end, the shell script or pipeline won't, too
  • 有人在入住前忘记删除暂停代码
    • 现在所有的工作伙伴都想知道为什么该应用程序不再关闭
    • 版本历史被污染
  • #define是地狱
  • 对于从控制台运行您的代码的任何人来说,这很烦人
  • 尝试从脚本中启动和结束程序时,这非常、非常、非常烦人;如果您的程序是 shell 中管道的一部分,那会很烦人,因为如果程序没有结束,shell 脚本或管道也不会结束

Instead, explore your IDE. It probably has an option not to close the console window after running. If not, it's a great justification to you as a developer worth her/his money to always have a console window open nearby.

相反,探索您的 IDE。它可能有一个选项,在运行后不关闭控制台窗口。如果没有,作为一名物有所值的开发人员,始终在附近打开一个控制台窗口是一个很好的理由。

Alternatively, you can make this a program option, but I personally have never seen a program with an option --keep-alive-when-dead.

或者,您可以将其设为程序选项,但我个人从未见过带有选项的程序--keep-alive-when-dead

Moral of the story:This is the user's problem, and not the program's problem. Don't taint your code.

故事寓意:这是用户的问题,而不是程序的问题。不要污染你的代码。

回答by Mr.C64

If you want to write portable C++ code, then I'd suggest using cin.get().

如果您想编写可移植的 C++ 代码,那么我建议使用cin.get().

system("PAUSE")works on Windows, since it requires the execution of a console command named "PAUSE". But I'm not sure that other operating systems like Linux or other Unix derivatives support that. So that tends to be non-portable.

system("PAUSE")适用于 Windows,因为它需要执行名为“ PAUSE”的控制台命令。但我不确定其他操作系统(如 Linux 或其他 Unix 衍生产品)是否支持。所以这往往是不可移植的。

Since C++ already offers cin.get(), I see no compelling reason to use C getch().

由于 C++ 已经提供了cin.get(),我认为没有令人信服的理由使用 C getch()

回答by Niall

The best waydepends a lot on the platform(s) being targeted, debug vs. release usage etc.

最好的方式在很大程度上取决于该平台(一个或多个)作为目标,调试与发布使用等

I don't think there is one bestway, but to "force" a wait on enter type scenario in a fairly generic way, especially when debugging (typically this is either compiled in or out based on NDEBUGor _DEBUG), you could try std::getlineas follows

我认为没有最好的方法,但是要以相当通用的方式“强制”等待输入类型场景,尤其是在调试时(通常这是基于NDEBUG或编译进或出_DEBUG),您可以尝试std::getline如下

inline void wait_on_enter()
{
    std::string dummy;
    std::cout << "Enter to continue..." << std::endl;
    std::getline(std::cin, dummy);
}

With our without the "enter to continue", as needed.

根据需要,我们没有“输入继续”。

回答by nameless

Which is best way to pause the console in C++ programs?

在 C++ 程序中暂停控制台的最佳方法是什么?

system("pause");and getch();(which comes from the DOS world, IIRC) are both unportable.

system("pause");getch();(来自 DOS 世界,IIRC)都是不可移植的。

Is cin.get() is better to use to pause console?

cin.get() 更适合用来暂停控制台吗?

As the only one portableand standardoption, I would say it is, but I personally believe one should not write interactive console programs, i.e. programs which actually pause the console or prompt for input (unless there is a reallygood reason for that, because that makes shell scripting much harder). Console programs should interact with the user via command line arguments (or at least that kind of interaction should be the default one).

作为唯一一个便携式标准的选择,我会说这是的,但我个人认为不应该写交互式控制台程序,即实际上暂停输入控制台或提示(除非有一个节目真的很好的理由,因为这使得 shell 脚本编写更加困难)。控制台程序应该通过命令行参数与用户交互(或者至少这种交互应该是默认的)。

Just in case you need pausing the program for the my-program-is-launched-from-the-IDE-and-immediately-closed-but-I-don't-have-enough-time-to-see-the-result reason — don't do that. Just configure your IDE or launch consoleprograms right from the console.

以防万一您需要暂停我的程序从 IDE 启动并立即关闭但我没有足够的时间查看-结果原因——不要那样做。只需配置您的 IDE 或直接从控制台启动控制台程序。

回答by ST3

There is no goodway to do that, but you should use portable solution, so avoid system()calls, in your case you could use cin.get()or getch()as you mentioned in your question, also there is one advice. Make allpauses controlled by one (or very few) preprocessor definitions.

没有好的方法可以做到这一点,但是您应该使用便携式解决方案,因此请避免system()调用,在您的情况下,您可以使用cin.get()getch()正如您在问题中提到的那样,还有一个建议。使所有暂停由一个(或极少数)预处理器定义控制。

For example:

例如:

Somewhere in global file:

全局文件中的某处:

#define USE_PAUSES
#ifndef _DEBUG    //I asume you have _DEBUG definition for debug and don't have it for release build
#undef USE_PAUSES
#endif

Somewhere in code

代码中的某处

#ifdef USE_PAUSES
cin.get();
#endif

This is not universal advice, but you should protect yourself from putting pausesin release builds and these should have easy control, my mentioned global filemay not be so global, because changes in that may cause really long compilation.

这不是普遍的建议,但您应该保护自己不要在发布版本中暂停,并且这些应该很容易控制,我提到的全局文件可能不是那么全局,因为其中的更改可能会导致编译时间过长。

回答by Marc.2377

(My answer is partially based on that from Yoank, and partially on a commentby Justin Timeon another question.)

(我的回答是部分地基于从Yoank,部分在评论贾斯汀时间上的另一个问题。)

cout << endl << "Press <Enter> to continue...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();

回答by Bob

Late response, but I think it will help others.

迟到的回应,但我认为这会帮助别人。

Part of imitating system("pause") is imitating what it asks the user to do: "Press any key to continue . . . " So, we need something that does not wait for simply a return as std::cin.get() would do. Even getch() has its problems when used twice (the second time call has been noticed to skip pausing generally if it's immediately paused again afterwards on the same key press). I think it has to do with the input buffer. System("pause") is usually not recommended, but we still need something to imitate what users might already expect. I prefer getch() because it doesn't echo to the screen, and it works dynamically.

模仿 system("pause") 的一部分是模仿它要求用户做的事情:“按任意键继续……”所以,我们需要一些不等待简单返回的东西,如 std::cin.get( ) 会做。即使 getch() 在使用两次时也有问题(第二次调用通常会跳过暂停,如果它随后在同一按键上立即再次暂停)。我认为这与输入缓冲区有关。System("pause") 通常不被推荐,但我们仍然需要一些东西来模仿用户可能已经期望的东西。我更喜欢 getch() 因为它不会回显到屏幕上,而且它是动态工作的。

The solution is to do the following using a do-while loop:

解决方案是使用 do-while 循环执行以下操作:

void Console::pause()
{ 
    int ch = 0;

    std::cout << "\nPress any key to continue . . . ";

    do {
        ch = getch();
    } while (ch != 0);

    std::cout << std::endl;
} 

Now it waits for the user to press any key. If it's used twice, it waits for the user again instead of skipping.

现在它等待用户按任意键。如果它被使用了两次,它会再次等待用户而不是跳过。

回答by Esoteric Eric

I always used a couple lines of code which clear the input stream of any characters and then wait for input to ignore.

我总是使用几行代码来清除任何字符的输入流,然后等待输入被忽略。

Something like:

就像是:

void pause() {
    cin.clear();
    cout << endl << "Press any key to continue...";
    cin.ignore();
}

And then any time I need it in the program I have my own pause(); function, without the overhead of a system pause. This is only really an issue when writing console programs that you want to stay open or stay fixated on a certain point though.

然后任何时候我在程序中需要它我都有自己的 pause(); 功能,没有系统暂停的开销。这只是在编写您希望保持打开状态或专注于某个点的控制台程序时才真正存在的问题。

回答by Yoank

This works for me.

这对我有用。

void pause()
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    std::string dummy;
    std::cout << "Press any key to continue . . .";
    std::getline(std::cin, dummy);
}

回答by Stian Svedenborg

I just want to add that there is a way to get what you want, but it will require to use some a third party library (or that you write the platform dependent code yourself).

我只想补充一点,有一种方法可以得到你想要的东西,但它需要使用一些第三方库(或者你自己编写依赖于平台的代码)。

As far as I'm concerned, the biggest drawback with cin is that you are required to hit Return, and not just any key.

就我而言,cin 的最大缺点是您需要按 Return,而不仅仅是按任意键。

Assuming you had a key-listener you could quite easily write a function that waits for the user to hit anykey. However finding a platform independent key listener is no trivial task, and will most likely require you to load parts of a larger library.

假设您有一个键侦听器,您可以很容易地编写一个函数来等待用户按任意键。然而,找到一个独立于平台的键侦听器并非易事,而且很可能需要您加载更大库的一部分。

I am thinking something along the lines of:

我正在考虑以下方面的事情:

char wait_for_key() {
    int key;
    while ( ! (key == key_pressed(ANY)) ) {
          this_thread::yield();
    }
    return convert_virtual_key_to_char(key);
}

The actual function would obviously be quite different from what I wrote, depending on the library you use.

实际功能显然与我写的有很大不同,这取决于您使用的库。

I know the following libraries have keylisteners (Feel free to add more in an edit if you know of any.):

我知道以下库具有密钥侦听器(如果您知道,请随时在编辑中添加更多内容。):