Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Timer (นาฬิกาจับเวลา) ใน C++ โดยใช้ System Calls

คำอธิบาย

ที่นี่เราจะดูวิธีออกแบบ Timer ใน C++ โดยใช้ system call เราจะไม่ใช้ graphics หรือ animation ตรงไหน ตรงนี้ Timer หมายถึง นาฬิกาจับเวลา (stopwatch) ที่นับเวลาขึ้นไป (up-counting) System calls ที่ใช้คือ:

sleep(n) – ช่วยให้โปรแกรมหยุดพัก (sleep) เป็นเวลา n วินาที

system() – ใช้สำหรับรันคำสั่งระบบ (system command) โดยส่งคำสั่งเป็น argument ให้ฟังก์ชันนี้

ตัวอย่างโค้ด

#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(); }

ผลลัพธ์

Timer (นาฬิกาจับเวลา) ใน C++ โดยใช้ System Calls