首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 記錄鍵盤連續輸入 6 個數字的時間間隔(毫秒級)

     編輯:程式設計綜合問答

需求

控制台程序讀取 6 次按鍵,記錄每次按鍵時間及相鄰間隔(毫秒精度)。

實現代碼

#include <iostream>
#include <ctime>
#include <conio.h>  // _getch() 無緩衝讀鍵
#include <vector>

struct KeyRecord {
    int keyCode;
    time_t timestamp;  // 秒級,若需毫秒用 clock_gettime/GetTickCount
};

int main() {
    std::vector<KeyRecord> records;
    std::cout << "請連續輸入 6 個數字鍵:" << std::endl;

    for (int i = 0; i < 6; ++i) {
        int ch = _getch();  // 非阻塞無回顯讀取
        KeyRecord rec = { ch, std::time(nullptr) };
        records.push_back(rec);
        std::cout << char(ch);  // 回顯
    }
    std::cout << std::endl;

    // 輸出詳細時間
    for (size_t i = 0; i < records.size(); ++i) {
        char buf[32];
        std::tm tm = *std::localtime(&records[i].timestamp);
        std::strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
        std::cout << "第 " << i+1 << " 鍵: '" << char(records[i].keyCode) << "' 時間: " << buf;
        if (i > 0) {
            double diff = std::difftime(records[i].timestamp, records[i-1].timestamp);
            std::cout << " 間隔: " << diff << " 秒";
        }
        std::cout << std::endl;
    }
    return 0;
}

毫秒級精度方案

  • Windows:GetTickCount64()(毫秒)、QueryPerformanceCounter(微秒)。
  • Linux:clock_gettime(CLOCK_MONOTONIC, &ts)(納秒)。
  • C++11 跨平台:std::chrono::high_resolution_clock::now()。

鍵盤 Hook 方案(全局監聽)

若需在**非控制台/後台**記錄全局按鍵,需安裝低級鍵盤鉤子(SetWindowsHookEx(WH_KEYBOARD_LL, ...)),在回調中記錄時間,複雜度高得多,控制台場景用 _getch + chrono 即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved