使用系統呼叫的 C++ 定時器
本文中,我們將介紹如何使用系統呼叫在 C++ 中設計一個定時器。我們不會使用任何圖形或動畫。這裡的定時器意味著秒錶,它可以對時間進行累加。使用到的系統呼叫如下 −
sleep(n) − 將幫助程式休眠 n 秒
system() − 透過將命令作為此函式的引數傳遞來執行系統命令。
示例
#include <iomanip> #include <iostream> #include <stdlib.h> #include <unistd.h> using namespace std; int hrs = 0; int mins = 0; int sec = 0; void showClk() { system("cls"); cout << setfill(' ') << setw(55) << " TIMER \n"; cout << setfill(' ') << setw(66) << " --------------------------------------\n"; cout << setfill(' ') << setw(29); cout << "| " << setfill('0') << setw(2) << hrs << " Hours | "; cout << setfill('0') << setw(2) << mins << " Minutes | "; cout << setfill('0') << setw(2) << sec << " Seconds |" << endl; cout << setfill(' ') << setw(66) << " --------------------------------------\n"; } void systemCallTimer() { while (true) { showClk(); sleep(1); sec++; if (sec == 60) { mins++; if (mins == 60) { hrs++; mins = 0; } sec = 0; } } } int main() { systemCallTimer(); }
輸出
廣告