用c++写一个计时器,每个两秒输出当前时间和数字1
时间: 2024-04-14 20:27:41 浏览: 173
好的,以下是一个使用C++编写的计时器程序,每两秒输出当前时间和数字1:
```cpp
#include <iostream>
#include <chrono>
#include <ctime>
#include <thread>
void timerFunction() {
while (true) {
// 获取当前时间
std::time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
// 输出当前时间和数字1
std::cout << "Current time: " << std::ctime(¤tTime);
std::cout << "Number: 1" << std::endl;
// 等待两秒
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
int main() {
// 启动计时器线程
std::thread timerThread(timerFunction);
// 主线程等待计时器线程结束
timerThread.join();
return 0;
}
```
这个程序使用了`<chrono>`库来获取当前时间,`<ctime>`库来格式化输出时间,并使用`<thread>`库中的`sleep_for`函数来等待两秒。计时器线程在一个无限循环中输出时间和数字1,直到程序结束。主线程等待计时器线程结束后程序才会退出。
请注意,在某些编译器上,`std::ctime`的返回值可能带有换行符`\n`,如果你不想输出换行符,可以使用`std::strftime`函数来自定义时间的格式化输出。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)