如何使用C ++中的计时器在给定时间内强制输入?

编程入门 行业动态 更新时间:2024-10-11 19:15:11
本文介绍了如何使用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(OUTPUT SCREEN):

EX(OUTPUT SCREEN):

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 << "\nTime-Out: 2 second:"; cout << "\nPlease enter the input:"; } cout << "You entered: " << value << '\n'; 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 ++中的计时器在给定时间内强制输入?

本文发布于:2023-11-30 00:01:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   时间内   如何使用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!