|
发表于 2019-7-30 16:37:38
|
显示全部楼层
本楼为最佳答案
本帖最后由 Croper 于 2019-7-30 16:45 编辑
利用thread制作的,不会影响正常输入,甚至可以同时运行多个的闹钟,输入"setclock:"+时间 设置闹钟- #include<iostream>
- #include<thread>
- #include<mutex>
- #include<time.h>
- #include<windows.h>
- #include<sstream>
- #include<string>
- using namespace std;
- mutex olock;
- //获取光标位置
- COORD getxy() {
- CONSOLE_SCREEN_BUFFER_INFO info;
- HANDLE hscr = GetStdHandle(STD_OUTPUT_HANDLE);
- GetConsoleScreenBufferInfo(hscr, &info);
- return info.dwCursorPosition;
- }
- //设置光标位置
- void gotoxy(int x, int y) {
- COORD coord = { x,y };
- HANDLE hscr = GetStdHandle(STD_OUTPUT_HANDLE);
- SetConsoleCursorPosition(hscr, coord);
- }
- //字符串转整数
- int s2i(string s) {
- stringstream ss(s);
- int ret;
- ss >> ret;
- return ret;
- }
- void SetClock(int delay) {
- olock.lock();
- COORD coord0 = getxy();
- cout << "闹钟已设置:剩余" << delay << "秒 \n";
- olock.unlock();
- time_t now = time(0);
- time_t target = time(0) + delay;
- while (target > now) {
- Sleep(1000);
- now = time(0);
- olock.lock();
- COORD coord = getxy();
- gotoxy(coord0.X, coord0.Y);
- cout << "闹钟已设置:剩余" << target - now << "秒 \n";
- gotoxy(coord.X, coord.Y);
- olock.unlock();
- }
- olock.lock();
- COORD coord = getxy();
- gotoxy(coord0.X, coord0.Y);
- cout << "闹钟时间到!! \n";
- gotoxy(coord.X, coord.Y);
- olock.unlock();
- }
- int main() {
- string s;
- cin >> s;
- while (s != "quit") {
- if (s.substr(0, 9) == "setclock:") {
- int t = s2i(s.substr(9, -1));
- if (t > 0) {
- thread thr(SetClock, t);
- thr.detach();
- }
- else {
- cout << "你不能设置时长为:" << t << "的闹钟" << endl;
- }
- }
- else {
- cout << "oops!\n";
- }
- cin >> s;
- }
- }
-
复制代码 |
|