
10

C++ 中非阻塞式的用户输入
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.

C++ 中非阻塞式的用户输入
如果我们用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.

前一篇:
妫水河骑行 35 公里
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK