How to use a timer in C++ to force input within a given time?(如何在 C++ 中使用计时器在给定时间内强制输入?)
问题描述
我想在 C++ 中实现超时功能.
I want to implement a time out feature in C++.
如果用户在 2 秒内没有输入值,那么程序必须显示超时语句并再次要求输入
If the user does not input the value within 2 seconds then the program must display the time-out statement and ask the input again
EX(输出屏幕):
Timer=0;
Please enter the input: //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input: //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input:22
Data accepted
Terminate the program`
代码:
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
clock_t endwait;
endwait = 2000 ;
cout<<endwait;
while (clock() < endwait)
{
cout<<"Please enter the input:";
}
return 0;
}
我已经研究了上面的代码.但这只会在进入 WHILE 循环时发生.我该如何做才能获得所需的输出.
I have worked on the above code. But this happens only while entering the WHILE loop. How shall i do it in a way so that, I get the required output.
推荐答案
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std;
condition_variable cv;
int value;
void read_value() {
cin >> value;
cv.notify_one();
}
int main()
{
cout << "Please enter the input: ";
thread th(read_value);
mutex mtx;
unique_lock<mutex> lck(mtx);
while (cv.wait_for(lck, chrono::seconds(2)) == cv_status::timeout)
{
cout << "
Time-Out: 2 second:";
cout << "
Please enter the input:";
}
cout << "You entered: " << value << '
';
th.join();
return 0;
}
输出:
Please enter the input:
Time-Out: 2 second:
Please enter the input:
Time-Out: 2 second:
Please enter the input:22
You entered: 22
这篇关于如何在 C++ 中使用计时器在给定时间内强制输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中使用计时器在给定时间内强制输入?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
