我想知道如何在用户输入诸如撰写特定句子之类的内容时创建可以停止的倒计时。
就我而言,我想做一些像西蒙所说的那样的事情。游戏。西蒙说' UP'所以你必须在两秒钟的时间内输入UP。如果您输入的内容不是' UP'倒计时停止,如果你输入' UP'它打破倒计时,说你赢了。当倒计时到零并且您没有输入任何内容时,您也会收到通知。
这是我到目前为止所写的内容:
#include <iostream>
#include <string>
#include <cmath>
#include<windows.h>
using namespace std;
int main() {
string answer;
int success = 0;
int counter = 0;
cout << "Simon says: UP" << endl;
for (int i = 2; i > 0; i--) {
cin >> answer;
if (answer == "UP") {
cout << "You win" << endl;
break;
}
else {
cout << "You lose" << endl;
}
}
return 0;
}
答案 0 :(得分:1)
如果不进入多线程,您可以尝试_kbhit(),这是一种与_getch()结合阅读用户输入的非阻塞方式,两者都在conio.h
#include <iostream>
#include <string>
#include <chrono>
#include <conio.h>
int main()
{
int timeout = 2; //2 seconds
std::string answer, say = "UP";
std::cout << "Simon says: " << say << std::endl;
std::cout << "You say: ";
// get start time point
std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
do
{
if (_kbhit()) // check user input
{
char hit = _getch(); // read user input
std::cout << hit; // show what was entered
if (hit == 13)
break; // user hit enter, so end it
answer += hit; // add char to user answer
}
}
while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start).count() < timeout);
// check if provided answer matches
if (answer == say)
std::cout << "\nYou win!" << std::endl;
else
std::cout << "\nYou lose!" << std::endl;
return 0;
}