控制台程序讀取 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;
}
GetTickCount64()(毫秒)、QueryPerformanceCounter(微秒)。clock_gettime(CLOCK_MONOTONIC, &ts)(納秒)。std::chrono::high_resolution_clock::now()。若需在**非控制台/後台**記錄全局按鍵,需安裝低級鍵盤鉤子(SetWindowsHookEx(WH_KEYBOARD_LL, ...)),在回調中記錄時間,複雜度高得多,控制台場景用 _getch + chrono 即可。