在控制台应用程序中,等待用户输入的最佳方法是什么?
std::cout << "press any key to exit...";
// wait for user to hit enter or another key
在控制台应用程序中,等待用户输入的最佳方法是什么?
std::cout << "press any key to exit...";
// wait for user to hit enter or another key
有几种方法可以做到这一点,以下是一些可能的一行代码:
使用 getch()
(需要 #include <conio.h>
)。
使用 getchar()
(期望为 Enter,需要 #include <iostream>
)。
使用 cin.get()
(期望为 Enter,需要 #include <iostream>
)。
使用 system("pause")
(需要 #include <iostream>
,仅适用于 Windows)。
PS:此方法还会在屏幕上打印 Press any key to continue . . .
。(似乎是你的完美选择:))
编辑:如此处所讨论,没有完全可移植的解决方案。问题19.1在comp.lang.c FAQ中涵盖了这个问题,提供了Windows、类Unix系统甚至是MS-DOS和VMS的解决方案。
使用do-while循环可以很好地等待用户输入。
就像这样:
int main()
{
do
{
cout << '\n' << "Press a key to continue...";
} while (cin.get() != '\n');
return 0;
}
你也可以使用函数system('PAUSE')
,但我认为这种方法较慢且依赖于平台。
std::cin
被关闭(因为get()
将返回EOF
),那么它将无限循环。 - Toby Speight\n
)之前输入了一个字符。在上面的代码中,该while循环会一直运行,直到cin.get()
获取到'\n'
。例如,如果您输入了3个字符并按下回车,则会提示“按任意键继续......”三次。 - starriet#include <iostream>
#include <conio.h>
int main() {
//some codes
getch();
return 0;
}
getch
在主函数里面还是其他地方? - doctorloveiostream
。 - herohuyongtao
std::cin.ignore();
- Stevoisiak