#include <thread> void timerThread() { initgraph(200, 200, SHOWCONSOLE); setbkcolor(RGB(225, 115, 100)); BeginBatchDraw(); Start_time = clock(); while (1) { cleardevice(); End_time = clock(); time_1 = (int)((End_time - Start_time) / CLOCKS_PER_SEC); settextstyle(20, 0, "宋体"); setcolor(BLACK); sprintf_s(str, " %d s", time_1); outtextxy(10, 10, str); EndBatchDraw(); } } int main() { // Run other loops here std::thread timer(timerThread); // Join the thread to wait for it to finish timer.join(); return 0; }如何使时间暂停
时间: 2024-03-05 14:50:13 浏览: 19
要使时间暂停,你需要在 timerThread() 函数中添加一个条件语句,以决定何时暂停时间。例如,你可以添加一个 bool 类型的变量 isPaused,并在 while 循环中检查它的值。如果 isPaused 为真,则不更新时间和绘制窗口。
以下是修改后的代码示例:
```c++
#include <thread>
void timerThread() {
initgraph(200, 200, SHOWCONSOLE);
setbkcolor(RGB(225, 115, 100));
BeginBatchDraw();
Start_time = clock();
bool isPaused = false; // 添加一个布尔变量
while (1) {
cleardevice();
End_time = clock();
if (!isPaused) { // 只有当 isPaused 为假时才更新时间和绘制窗口
time_1 = (int)((End_time - Start_time) / CLOCKS_PER_SEC);
settextstyle(20, 0, "宋体");
setcolor(BLACK);
sprintf_s(str, " %d s", time_1);
outtextxy(10, 10, str);
EndBatchDraw();
}
}
}
int main() {
// Run other loops here
std::thread timer(timerThread);
// 在这里添加暂停时间的代码
bool isPaused = false;
while (1) {
// 检查键盘输入
if (kbhit()) {
char ch = getch();
if (ch == 'p' || ch == 'P') {
isPaused = !isPaused; // 切换 isPaused 的值
}
}
// 如果时间暂停,则等待一段时间再继续运行
if (isPaused) {
Sleep(100);
}
}
// Join the thread to wait for it to finish
timer.join();
return 0;
}
```
在上面的代码中,我们在主循环中添加了暂停时间的代码。当用户按下 'p' 键时,isPaused 的值将被切换。在 timerThread() 函数中,只有当 isPaused 为假时才更新时间和绘制窗口。如果 isPaused 为真,则等待一段时间(例如 100 毫秒)再继续运行。这样就可以实现暂停时间的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)