开发者

Console pause in C++?

开发者 https://www.devze.com 2023-01-27 23:16 出处:网络
In C# you can cause the console to wait for a character to be input (whi开发者_运维问答ch is useful for being able to see the last outputs of a console before the program exits). As a beginner in C++,

In C# you can cause the console to wait for a character to be input (whi开发者_运维问答ch 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?


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.


#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):

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


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.


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).

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:

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

This effectively prevents the console from flashing and then exiting.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号