在控制台应用程序中等待用户输入的最佳方式是什么? std::cout << "press any key to exit..."; // wait for user to hit enter or another key 原文由 Ivars 发布,翻译遵循 CC BY-SA 4.0 许可协议
有几种方法可以做到这一点,这里有一些可能的单线方法: 使用 getch() (需要 #include <conio.h> )。 使用 getchar() (预期为 Enter ,需要 #include <iostream> )。 使用 cin.get() (预期为 Enter ,需要 #include <iostream> )。 使用 system("pause") (需要 #include <iostream> , 仅限 Windows )。 PS:这个方法也会在屏幕上打印 Press any key to continue . . . 。 (对你来说似乎是完美的选择:)) 编辑: 正如 这里 所讨论的,没有完全可移植的解决方案。 comp.lang.c FAQ 的问题 19.1 对此进行了深入的讨论,提供了适用于 Windows、类 Unix 系统甚至 MS-DOS 和 VMS 的解决方案。 原文由 herohuyongtao 发布,翻译遵循 CC BY-SA 4.0 许可协议
do while 循环将是等待用户输入的好方法。像这样: int main() { do { cout << '\n' << "Press a key to continue..."; } while (cin.get() != '\n'); return 0; } 您也可以使用功能 system('PAUSE') 但我认为这有点慢并且取决于平台 原文由 CMS 发布,翻译遵循 CC BY-SA 3.0 许可协议
有几种方法可以做到这一点,这里有一些可能的单线方法:
使用
getch()
(需要#include <conio.h>
)。使用
getchar()
(预期为Enter
,需要#include <iostream>
)。使用
cin.get()
(预期为Enter
,需要#include <iostream>
)。使用
system("pause")
(需要#include <iostream>
, 仅限 Windows )。PS:这个方法也会在屏幕上打印
Press any key to continue . . .
。 (对你来说似乎是完美的选择:))编辑: 正如 这里 所讨论的,没有完全可移植的解决方案。 comp.lang.c FAQ 的问题 19.1 对此进行了深入的讨论,提供了适用于 Windows、类 Unix 系统甚至 MS-DOS 和 VMS 的解决方案。