C 等待用户输入

新手上路,请多包涵

在控制台应用程序中等待用户输入的最佳方式是什么?

 std::cout << "press any key to exit...";
// wait for user to hit enter or another key

原文由 Ivars 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

有几种方法可以做到这一点,这里有一些可能的单线方法:

  1. 使用 getch() (需要 #include <conio.h> )。

  2. 使用 getchar() (预期为 Enter ,需要 #include <iostream> )。

  3. 使用 cin.get() (预期为 Enter ,需要 #include <iostream> )。

  4. 使用 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题