C++ 如何实现“按任意键退出”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9347633/
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
How to implement "Press Any Key To Exit"
提问by Inside Man
Here is a simple code in C++:
这是一个简单的 C++ 代码:
cout << "Press Any Key To Exit...";
What is the code for closing program when user presses any button on keyboard. What should I write after above code? I know I can use cin.ignore(); and if user presses Enter the program will close, But my target is any key.
当用户按下键盘上的任何按钮时关闭程序的代码是什么。上面的代码后我应该写什么?我知道我可以使用 cin.ignore(); 如果用户按 Enter 程序将关闭,但我的目标是任意键。
How to do that?
怎么做?
回答by Necrolis
回答by Ivaylo Strandjev
Try this:
system("pause");
It will hold until any key is pressed.
试试这个:
system("pause");
它会一直保持,直到按下任何键。
EDIT: please read comments below before deciding on this alternative
编辑:在决定这个替代方案之前,请阅读下面的评论
回答by howardh
You can use the ncurses library to do this. The downside to this solution is that you won't be able to use cout for outputting anymore.
您可以使用 ncurses 库来执行此操作。此解决方案的缺点是您将无法再使用 cout 进行输出。
#include <ncurses.h>
int main()
{
initscr();
printw("Press Any Key To Exit...");
getch();
endwin();
}
Be sure to -lncurses
when compiling
-lncurses
编译的时候一定要
回答by Shashank Kadne
getch()
, getche()
, system("pause")
, exit(0)
...should work.
getch()
, getche()
, system("pause")
, exit(0)
...应该工作。