mgeraci
mgeraci

Reputation: 3

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

I need the user input to press a key within a time range. If he doesn't press any key, the seconds variable is incremented. Below you can find the flowchart and my code.

    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.
    }

enter image description here

Upvotes: 0

Views: 613

Answers (1)

Anonymous1847
Anonymous1847

Reputation: 2598

You can count how many seconds it took for the user to input a character:

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.
}

Alternatively, on POSIX systems you could use a select() call to block until input arrives, or until a timeout expires.

Or, you could use std::istream::readsome in a polling loop:

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

Or you could run the seconds incrementing in a separate thread.

Upvotes: 2

Related Questions