Non-blocking console input C++

Doug picture Doug · May 30, 2011 · Viewed 44.8k times · Source

I'm looking for a (multiplatform) way to do non-blocking console input for my C++ program, so I can handle user commands while the program continually runs. The program will also be outputting information at the same time.

What's the best/easiest way to do this? I have no problem using external libraries like boost, as long as they use a permissive license.

Answer

Sascha picture Sascha · Dec 12, 2017

Example using C++11:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>

static std::string getAnswer()
{    
    std::string answer;
    std::cin >> answer;
    return answer;
}

int main()
{

    std::chrono::seconds timeout(5);
    std::cout << "Do you even lift?" << std::endl << std::flush;
    std::string answer = "maybe"; //default to maybe
    std::future<std::string> future = std::async(getAnswer);
    if (future.wait_for(timeout) == std::future_status::ready)
        answer = future.get();

    std::cout << "the answer was: " << answer << std::endl;
    exit(0);
}

online compiler: https://rextester.com/GLAZ31262