You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ctime使用问题:程序时间无法每秒更新,寻求技术帮助

问题分析与解决

你的代码时间冻结的核心原因有两个:

  • getch()是阻塞式函数,程序执行到这里会一直等待用户按键,只有按下键才会进入下一次循环更新时间,自然无法实现每秒自动刷新。
  • 时间获取和循环逻辑顺序不合理,导致每次循环的时间是固定的,且被按键输入阻塞打断。

修复后的代码

#include <iostream>
#include <conio.h>
#include <chrono>
#include <thread>
#include <ctime>

using namespace std;

int main() {
    do {
        // 获取当前最新时间
        time_t curr_time = time(NULL);
        tm* tm_local = localtime(&curr_time);
        
        // 清屏并打印时间
        system("CLS");
        cout << "Current time : " << tm_local->tm_hour << ":" << tm_local->tm_min << ":" << tm_local->tm_sec << endl;
        cout << "To exit the clock click space" << endl;

        // 非阻塞检查是否有按键输入
        if (_kbhit()) {
            char ch = getch();
            if (ch == ' ') {
                system("CLS");
                break;
            }
        }

        // 等待1秒后进入下一次循环更新时间
        this_thread::sleep_for(chrono::seconds(1));
    } while (true);

    return 0;
}

关键修改点说明

  • 用_kbhit()做非阻塞按键检测:它会立即返回是否有按键按下,不会阻塞程序执行,保证时间能每秒正常刷新。
  • 调整逻辑顺序:先获取时间、刷新显示,再检查按键,最后sleep,确保每一秒都会更新一次时间。
  • 移除不必要的goto main:直接用break退出循环即可,goto会让程序重新进入main函数,容易引发栈溢出问题,完全没必要。

内容的提问来源于stack exchange,提问作者DaGreyKar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:55:00