10

C++ 中非阻塞式的用户输入

 4 years ago
source link: https://zhiqiang.org/coding/noblock-input.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++ 中非阻塞式的用户输入

作者: 张志强

, 发表于 2021-09-02

, 共 498 字 , 共阅读 12 次

如果我们用std::getline或者简单的std::cin >>获取用户输入,有一个问题是,它会阻塞掉整个程序,用户必须有输入后才能继续执行。如果这个输入是单独的线程,它还会阻止整个程序的退出。

这个时候可以用下面这个函数,非阻塞式的用户输入,会检查用户是否在输入,没有的话就直接返回空:

#include <iostream>
#include <optional>

std::optional<std::string> noblock_input(std::istream& in = std::cin)
{
    if (in.rdbuf()->in_avail() != -1) {
        char buffer[1024];

        in.getline(buffer, sizeof(buffer));

        return buffer;
    }

    return {};
}

注意,该实现在用户已有输入字符的情况下,会等到用户输入到按下回车为止,在这期间是也是阻塞的。

Q. E. D.

avatar-0.jpg
跟着绿野的商业队伍去妫水河骑行,每人 198 元,惠新西街南口大巴接送往返。自行车取车地是世界葡萄博览园的南门。自驾也可以在此处租车,每车 150 元。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK