如何在 C++ 中使用计时器在给定时间内获取用户输入?

How to use a timer in C++ to get a user input within a given time?

我需要用户输入在一个时间范围内按下一个键。如果他不按任何键,则秒变量会增加。您可以在下面找到流程图和我的代码。

    int DisplayMenu() //This function displays the user menu.
    {
        int userChoice{};
        cout << "\t\t***************************" << endl;
        cout << "\t\t* 1-Add One Hour          *" << endl;
        cout << "\t\t* 2-Add One Minute        *" << endl;
        cout << "\t\t* 3-Add One Second        *" << endl;
        cout << "\t\t* 4-Exit Program          *" << endl;
        cout << "\t\t***************************" << endl;
        // while time < 1 sec
        //check userChoice
        // if !userChoice increments seconds
        cin >> userChoice;
        return userChoice; //The value returned will be use as argument for the UserChoice function.
    }

您可以计算用户输入一个字符所用的秒数:

int DisplayMenu() //This function displays the user menu.
{
    int userChoice{};
    cout << "\t\t***************************" << endl;
    cout << "\t\t* 1-Add One Hour          *" << endl;
    cout << "\t\t* 2-Add One Minute        *" << endl;
    cout << "\t\t* 3-Add One Second        *" << endl;
    cout << "\t\t* 4-Exit Program          *" << endl;
    cout << "\t\t***************************" << endl;
    std::chrono::timepoint before = std::chrono::high_resolution_clock::now();
    cin >> userChoice;
    std::chrono::timepoint after = std::chrono::high_resolution_clock::now();
    seconds += std::chrono::floor<std::chrono::seconds>(after - before).count();
    return userChoice; //The value returned will be use as argument for the UserChoice function.
}

或者,在 POSIX 系统上,您可以使用 select() 调用来阻止直到输入到达,或直到超时到期。

或者,您可以在轮询循环中使用 std::istream::readsome

char c;
std::chrono::timepoint p = std::chrono::high_resolution_clock::now();
while (std::cin.readsome(&c, 1) == 0) { // while no characters available
    std::chrono::timepoint n = std::chrono::high_resolution_clock::now();
    if (std::chrono::floor<std::chrono::seconds>(n - p).count() == 1) {
        ++seconds;
        p = n;
    }
}
// now c contains a character input

或者您可以 运行 seconds 在单独的线程中递增。