ที่นี่เราจะมาดูวิธีออกแบบตัวจับเวลาใน C++ โดยใช้การเรียกของระบบ เราจะไม่ใช้กราฟิกหรือแอนิเมชั่นใดๆ ตัวจับเวลาในที่นี้หมายถึงนาฬิกาจับเวลาซึ่งกำลังนับเวลาขึ้น การเรียกระบบที่ใช้คือ −
นอน(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();
} ผลลัพธ์
