如标题所示,我正在用标准库测试某些东西,而我对如何确定何时收到准确的输入感到困惑。我的代码如下所示:
static bool s_cinGet = false;
std::string CycleWords(std::vector<std::string> Words)
{
unsigned int i = 0;
while (!s_cinGet)
{
system("cls");
std::cout << Words[i] << std::endl;
i++;
i = i % Words.size();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
if (i != 0) i--;
else i = Words.size() - 1;
return Words[i];
}
int main()
{
std::vector<std::string> Words = { "Tunti", "Triliteral", "Carl" };
while (true)
{
s_cinGet = false;
auto future = std::async(CycleWords, Words);
std::cin.get();
s_cinGet = true;
std::string word = future.get();
//system("cls");
std::cout << word << std::endl;
}
std::cin.get();
return 0;
}
该程序非常简单。它会循环显示某些单词,直到用户按任意键并打印最后一个单词为止。我想确保当用户按下一个键时,最后一个单词是完全相同的单词。任何建议表示赞赏。
最佳答案
正如@PeteBecker所建议的那样,将s_cinGet
从bool
更改为std::atomic<bool>
摆脱了未定义的行为。问题解决了。
关于c++ - 在C++中收到输入时如何停止执行异步功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60381964/