c++ - 非阻塞控制台输入 C++

标签 c++ console io nonblocking

我正在寻找一种(多平台)方法来为我的 C++ 程序进行非阻塞控制台输入,这样我就可以在程序持续运行时处理用户命令。该程序还将同时输出信息。

最好/最简单的方法是什么?只要使用许可许可证,我就可以使用诸如 boost 之类的外部库。

最佳答案

使用 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);
}

在线编译器:https://rextester.com/GLAZ31262

关于c++ - 非阻塞控制台输入 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171132/

相关文章:

c++ - 为什么 cin.ignore() 请求输入?

javascript - e = 控制台信息;不在 chrome 中工作

swift - 单元测试 WKNavigationDelegate 函数

generics - 如何使用用户输入变量作为通用包的参数?

c++ - 类继承出错?

c++ - G++ 错误 : In file included, 然后未声明 Foo

javascript - 如何使用 JavaScript 触发打开控制台 (F12) 事件?

c# - 如何检查重复图像? C#

c# - 为什么这在 C++ 中要慢得多?

c++ - 为什么此代码不会导致死锁?