gpt4 book ai didi

c++ - 如何给用户分配一定的时间回答?

转载 作者:行者123 更新时间:2023-11-30 02:41:26 26 4
gpt4 key购买 nike

像秒表一样,给正在使用我的程序的人大约30秒钟回答,如果没有答案退出程序?
基本上,响应时间不应超过给定的时间,否则程序将退出。

最佳答案

如果您不想使用exit并终止该进程,则可以这样进行:

std::string getInputWithin(int timeoutInSeconds, bool *noInput = nullptr)
{
std::string answer;

bool exceeded = false;
bool gotInput = false;

auto r1 = std::async([&answer, &gotInput]()
{
std::getline(std::cin, answer);
gotInput = true;
});

auto r2 = std::async([&timeoutInSeconds, &exceeded]()
{
std::this_thread::sleep_for(std::chrono::seconds(timeoutInSeconds));
exceeded = true;
});

while(!gotInput && !exceeded)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}

if(gotInput)
{
if(noInput != nullptr) *noInput = false;
return answer;
}

if(noInput != nullptr) *noInput = true;
return "";
}

int main()
{
std::cout << "please answer within 10 seconds...\n";

bool noInput;
std::string answer = getInputWithin(10, &noInput);

return 0;
}

这样做的好处是,您现在可以使用默认值来处理丢失的输入,或者只是给用户第二次机会,等等。

关于c++ - 如何给用户分配一定的时间回答?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28097399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com