C++简单计时器代码(无EasyX)

源代码(含解析)

#include <iostream> //系统输入流 
#include <conio.h> //用于键盘检测 
#include <Windows.h>//用于Sleep(); 

//标准命名空间 
using namespace std;

//正计时函数 
void Time01()
{
    bool pause = false;
    int s = 0;
    int m = 0;
    cout << "Press anything to start." << endl;
    getch();
    while (1)
    {
        if (kbhit())
        {
            char input = getch();
            
			//按空格暂停和继续 
			if (input == ' ') pause = !pause;
            
			//按Esc退出 
			else if (input == 27) 
            {
                cout << "Stop." << endl; 
                break;
            }
        }
        
		//正常计时 
		else if (!pause)
        {
            //清屏 
			system("cls");
			
			//显示当前时间 
            cout << "Time:" << m << ":" << s << endl << "Press space to pause.\nPress Esc to stop." << endl;
            
			s++;
            
			//更新分钟数m 
			if (s == 60) 
            {
                s = 0; 
                m++;
            }
            Sleep(1000);
        }
    }
    getch(); //按任意键继续 
}

//倒计时函数 
void Time02()
{
    bool pause = false;
    int s = 0; //秒数 
    int m = 0; //分钟数 
    cout << "Enter the minutes:";
    cin >> m;
    cout << "Enter the seconds:";
    cin >> s;
    system("cls");
    cout << "Press anything to start." << endl;
    getch();
    while (1)
    {
        if (kbhit())
        {
            //获取键盘输入 
			char input = getch();
            
			//空格暂停与继续 
			if (input == ' ') pause = !pause;
            
			//Esc退出 
			else if (input == 27) 
            {
                cout << "Stop." << endl; 
                break;
            }
        }
        
		//正常计时 
		else if (!pause)
        {
            system("cls");
            cout << "Time:" << m << ":" << s << endl << "Press space to pause.\nPress Esc to stop." << endl;
            s--;
            if (s == -1 && m > 0) 
            {
                s = 59; 
                m--;
            }
            
			//计时结束 
			else if (s == -1 && m == 0)
            {
                cout << "\a\a\a\a\aTime's up." << endl;
                break;
            }
            Sleep(1000);
        }
    }
    getch();
}

int main()
{
    system("title Timer");
    cout << "Timer" << endl;
    cout << "Press anything to begin.";
    getch();
    system("cls");
    cout << "\aChoose mod.\n1.Positive timing 2.countdown" << endl << ">>>";
    int mod;
    cin >> mod;
    switch(mod)
    {
        case 1: Time01(); break;
        case 2: Time02(); break;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值