如何创建基于计时器的用户输入输入? [英] How Can I Create A Timer Based User Entry Input?

查看:74
本文介绍了如何创建基于计时器的用户输入输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是我会问用户一个问题并说我将提供10秒钟来回答该问题。如果用户退出给定时间,则程序终止。但即使时间已经超过,我似乎无法终止该计划。基本上我的意思是程序仍然在等待用户的输入。

我无法理解如何修复此错误。请提出任何建议!谢谢



My goal is that i will ask a user a question and say i will provide 10 seconds to answer that question.If the user exits the given time then the program terminates. But even though the time has been exceeded, i cant seem to terminate the program. Basically what i mean is that the program still keeps waiting for the user's input.
I cant understand how to fix this error. Please any suggestions! Thanks

#include<iostream>
#include <ctime>
#include<stdlib.h>
#include <conio.h>
#include <string>
#include <Windows.h>

using namespace std;

int main()
{
time_t begin,end;
bool flag = true;
string ch;

begin = time(NULL);
while(flag)
{
  end = time(NULL);
  
  if(difftime(end,begin)<30)
   {
    cout<<"Enter your answer"<<endl;
    getline(cin,ch);
   }

  if(difftime(end,begin)>30)
   {
    flag = false;
    cout<<"Sorry you are timed out"<<endl;
   }
}

system("pause");
}

推荐答案

我的建议是重新设计。



1.你的主代码属于一个单独的线程函数。

2.在你的(新)主函数中,你启动线程并等待10秒(也许100等待100毫秒睡眠)并检查输入。输入缓冲区必须是全局的!
My suggestion would be a redesign.

1. your main-code belongs in a separate thread function.
2. in your (new) main function you start thread and wait up to 10 sec (maybe 100 waits of 100 ms Sleep) and check for the input. The input buffer must be global!!!


这篇关于如何创建基于计时器的用户输入输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆