这应该是一个正常的计时器,它会一直运行到被暂停或退出,代码由NextStep()函数退出,计时器应该暂停并保持暂停状态,直到它被再次按下。
但是,当我按空格键时,计时器只有在向计时器添加另一个数字后才会停止。
这个问题的一个例子:
01秒
02秒
我按空格键。
03秒(+1秒)
计时器暂停。
另一方面,执行NextStep()的代码工作正常,没有任何延迟。
我试着用不同的方法重写它,但都不起作用。
#pragma once
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <stdlib.h>
#include <iomanip>
#include <math.h>
#include <windows.h>
#include <conio.h>
#include <thread>
using namespace std;
void NextStep();
bool pause = false;
bool stop = false;
void wait(int milliseconds)
{
int counter = 0;
while (pause) {
char ch = _getch();
if (ch == ' ')
{
pause = !pause;
}
else if (ch == 27)
{
cout << "\033c";
NextStep();
stop = true;
}
}
while (counter < milliseconds && !stop)
{
if (pause) {
continue;
}
if (pause == false) {
this_thread::sleep_for(chrono::milliseconds(1));
counter++;
}
}
}
void timer()
{
int seconds = 0;
int minutes = 0;
int hours = 0;
while (true)
{
cout << "\033c";
cout << setfill(' ') << setw(55) << " Timer \n";
cout << " ";
cout << setfill('0') << setw(2) << hours << "h ";
cout << setfill('0') << setw(2) << minutes << "min ";
cout << setfill('0') << setw(2) << seconds << "sec ";
wait(60);
seconds++;
if (seconds == 60) {
minutes++;
seconds = 0;
}
else if (minutes == 60)
{
hours++;
minutes = 0;
seconds = 0;
}
if (_kbhit())
{
char ch = _getch();
if (ch == ' ')
{
pause = !pause;
}
else if (ch == 27)
{
cout << "\033c";
NextStep();
stop = true;
break;
}
}
}
}
下面是NextStep()函数:
void NextStep()
{
string option;
correct = false;
cout << "\033c";
cout << "Loading...";
Sleep(1300);
cout << "\033c";
cout << "What would you like to do next?" << endl;
cout << "" << endl;
cout << "To change your password TYPE: password" << endl;
cout << "To use a calculator TYPE: calculator" << endl;
cout << "To use a timer TYPE: timer" << endl;
cout << "" << endl;
cout << "Type your choice: ";
UserInput();
}
1条答案
按热度按时间9rnv2umw1#
我不确定我是否理解了你代码的所有工作原理,但是我想我理解了你需要一个可以启动、暂停和重新启动的计时器。另外,如果我理解正确的话,计时器不应该受到线程处于睡眠状态这一事实的影响。
因此,下面是这样一个计时器的实现,它可能会对您有所帮助(至少对您的问题的一部分):
下面是一个如何使用它的示例:
Timer
是一个模板,因此您可以使用以下任意类型来代替std::chrono::seconds
,具体取决于计时器所需的精度: