如何在不导致代码停止执行的情况下进行输入?在过去的 20 分钟里,我一直在寻找答案,但没有结果。
cin >> string;
暂停代码 AFAIK。
我需要使用多线程,还是有更好的方法? (我什至不知道多线程是否可行。)
我最近开始学习c++,至少可以说我是初学者,所以请详细解释并包括我可能需要的任何库,谢谢。
最佳答案
这是一个示例,说明如何使用 >>>
与另一个使用多线程的调用并行地从标准输入流中读取 token 。
#include <iostream>
#include <thread>
#include <future>
int main() {
// Enable standard literals as 2s and ""s.
using namespace std::literals;
// Execute lambda asyncronously.
auto f = std::async(std::launch::async, [] {
auto s = ""s;
if (std::cin >> s) return s;
});
// Continue execution in main thread.
while(f.wait_for(2s) != std::future_status::ready) {
std::cout << "still waiting..." << std::endl;
}
std::cout << "Input was: " << f.get() << std::endl;
}
此处调用std::async
使用启动参数 std::launch::async
在不同的线程上异步运行任务。 std::async
返回并行运行的任务句柄,称为 future。这个 future 可用于检查任务是否完成。任务的结果也可以从 std::future
返回。使用成员函数的对象 std::future::get
.
我传递给 std::async
的任务很简单 lambda expression创建一个字符串,从流中读取一个标记到字符串中并返回它(""s
是 C++14 中引入的标准文字,它返回一个空的 std::string
对象)。
在调用 std::async
之后,主线程继续执行语句(与异步运行的任务并行)。在我的示例中,执行了一个 while
循环,它只是等待异步任务完成。注意 std::future::wait_for
的使用每次迭代只阻塞 2 秒。 std::future::wait_for
返回一个status,可以将其进行比较以检查任务是否完成。
最后调用 std::future::get
将返回异步运行任务的结果。如果我们没有等待任务完成,调用将阻塞直到结果准备好。
注意不要在主线程中也(并行地)读取标准输入,因为读取调用不是原子事务,数据可能会出现乱码。
关于c++ - 无需暂停代码的用户输入(C++ 控制台应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127073/