How to implement a timeout for getline ()?

I want to read a line from the command line through getline()in C ++.

For this, I want to add a timer 5sec. If no lines are read, the program will exit.

How can i do this?

+5
source share
2 answers

ok, wait 5sec and terminateif the input was not:

#include <thread>
#include <atomic>
#include <iostream>
#include <string>

int main()
{
    std::atomic<bool> flag = false;
    std::thread([&]
    {
        std::this_thread::sleep_for(std::chrono::seconds(5));

        if (!flag)
            std::terminate();
    }).detach();

    std::string s;
    std::getline(std::cin, s);
    flag = true;
    std::cout << s << '\n';
}
+7
source

What about:

/* Wait 5 seconds. */
alarm(5);

/* getline */

/* Cancel alarm. */
alarm(0);

Alternatively you can use setitimer.


As R. Martigno Fernandez said:

The function alarmorders the current process to receive SIGALRM 5 seconds after it is called. The default action for SIGALRMsi to abort the process is abnormal. A call alarm(0)disables the timer.

+4

All Articles