#include <iostream>
#include <map>
#include <vector>
#include <memory>
#include <string>
#include <stdexcept>
#include <chrono>
#include <thread>
template<typename ... Args>
std::string stringFormat(const std::string& format, Args ... args)
{
int n = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1;
if (n <= 0) {
throw std::runtime_error("Error during formatting."); // 异常处理
}
auto size = static_cast<size_t> (n);
std::unique_ptr<char[]> buf(new char[size]); // 智能指针实现,防止内存泄漏
std::snprintf(buf.get(), size, format.c_str(), args ...);
return std::string(buf.get(), buf.get() + size - 1);
}
using std::string;
class Time {
public:
int h, m, s;
string clock; // 显示时间格式 hh:mm:ss
Time(int, int, int);
Time operator ++ (int);
bool operator != (const Time&) const;
};
Time::Time(int hour, int minute, int second) : h(hour), m(minute), s(second) {
string format = "%02d:%02d:%02d";
clock = stringFormat(format, h, m, s);
}
Time Time::operator ++ (int) {
++s;
if (s >= 60) {
++m;
s -= 60;
}
if (m >= 60)
{
++h;
m -= 60;
}
string format = "%02d:%02d:%02d";
clock = stringFormat(format, h, m, s);
return Time(h, m, s);
}
bool Time::operator != (const Time &T)const {
return (h != T.h) || (m != T.m) || (s != T.s);
}
using std::map, std::vector;
using std::cout, std::endl;
namespace Digits {
map<char, vector<string>> digits = {
{'0', { "#####", "# #", "# #", "# #", "#####" } },
{'1', { " # ", " ## ", " # ", " # ", " ### " } },
{'2', { "#####", " #", "#####", "# ", "#####" } },
{'3', { "#####", " #", "#####", " #", "#####" } },
{'4', { "# #", "# #", "#####", " #", " #" } },
{'5', { "#####", "# ", "#####", " #", "#####" } },
{'6', { "#####", "# ", "#####", "# #", "#####" } },
{'7', { "#####", " #", " #", " #", " #" } },
{'8', { "#####", "# #", "#####", "# #", "#####" } },
{'9', { "#####", "# #", "#####", " #", "#####" } },
{':', { " ", " [] ", " ", " [] ", " " } },
};
void display(Time T) {
for (int i = 0; i < 5; i++) {
for (const char& c : T.clock) {
cout << digits[c][i] << " ";
}
cout << endl;
}
}
}
void countDown(Time end) {
Time start(0, 0, 0);
using namespace Digits;
while (start != end) {
system("cls");
display(start);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
start++;
}
system("cls");
display(start);
}
int main(void) {
Time T(0, 1, 13); // 计时
countDown(T);
return 0;
}