使用std::cin持续暂停用户输入



我正在编写一个终端应用程序,我想在某些时候暂停程序,等待用户再继续。我想避免依赖操作系统的代码,所以我不使用Press any key to continue . . .,请参阅此答案。我决定下一个最好的东西是Press enter to continue . . .,但我无法让它可靠地工作。

我已经尝试了以下方法来暂停用户输入换行符,但没有成功。

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n')`;
std::string foo;
getline(std::cin, foo);
char foo{0};
std::cin >> std::noskipws;
while(foo != 'n') {
std::cin >> foo;
}
std::cin >> std::skipws;

问题是,我使用std::basic_istream& operator>>(int)std::basic_istream& operator>>(char)获得用户输入,这会留下尾随的空白。因此,如果我在调用puaseForEnter()函数之前收到输入,那么它不会暂停,但如果我连续调用pauseForEnter()两次,中间有一些输出,它会正常工作。将暂停代码增加一倍有时会要求用户按回车键两次。

我相信检测到任何其他角色都会遇到同样的问题。

我寻找了一种方法来清除流(消耗流中当前的所有字符(而不使其暂停,但我没有看到任何方法。还有其他方法可以实现我想要的吗?

我决定只检查换行符是否输入得"太快"。我不喜欢这个解决方案,因为它可能是不可编程的,但它在大多数情况下都会起作用。

void pauseForEnter() {
std::cout << "Press Enter to continue ...";
auto start{std::chrono::system_clock::now()};
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() < 10) {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); }
}

最新更新