Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-blocking console input C++

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.

like image 799
Doug Avatar asked May 29 '11 23:05

Doug


1 Answers

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

like image 72
Sascha Avatar answered Sep 28 '22 04:09

Sascha