Thiết kế đồng hồ bấm giờ (stopwatch) đếm ngược thời gian trong C++ dùng system call. Không dùng đồ họa/hoạt ảnh.
System calls sử dụng
- sleep(n): Ngủ n giây
- system(): Thực thi lệnh hệ thống (ví dụ: "cls" xóa màn hình Windows)
Chương trình C++
#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int hrs = 0, mins = 0, sec = 0;
void showClk() {
system("cls"); // Windows: "cls", Linux/Mac: "clear"
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();
}
Kết quả

Lưu ý
system("cls")chỉ chạy trên Windows. Linux/Mac dùngsystem("clear")sleep()từ<unistd.h>(POSIX). Windows dùngSleep()từ<windows.h>(miligiây)- Chương trình chạy vô hạn, dùng Ctrl+C để dừng