c++ - 这个程序如何从 C++ 中的 struct time 连续更新和打印时间?
问题描述
我正在研究一个不断更新时间的程序,我对它的工作原理有一些疑问。
当我注释掉 while(1) 循环时,程序仍然运行但不打印时间。为什么需要while循环?制作一个始终进行的while循环不是一个坏主意吗?连续的while循环是否每秒运行一次if循环?
从存储总秒数到 time(0) 的行,time(0) 是什么数据类型?它是一个整数吗?如果是这样,为什么后面是(0)?如果我将 0 更改为 1,则会出现以下错误:
C:\Users\Roman Justice\Desktop\Clock_1.cpp In function 'int main()':
C:\Users\Roman Justice\Desktop\Clock_1.cpp [Error] invalid conversion from 'int' to 'time_t* {aka long long int*}' [-fpermissive]
这个错误是说 time_t total_seconds 正在转换为 long long int 吗?
“seconds=ct->tm_sec;”这一行的含义是什么?这是否会将 struct time 的一部分转换为可读或可打印的格式?
对于 if 语句,我对“sec_prev=seconds;”这行感到困惑 和“秒==sec_prev+1”。第一行将 sec_prev 分配给秒,这是否意味着它们将始终相同?在 cout 语句中,为什么时间编码为 ("hours<10?"0":"") 而不仅仅是 "hours"?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
int sec_prev=0;
while(1)
{
int seconds, minutes, hours;
string str;
//storing total seconds
time_t total_seconds=time(0);
//getting values of seconds, minutes, hours
struct tm* ct=localtime (&total_seconds);
seconds=ct->tm_sec;
minutes=ct->tm_min;
hours=ct->tm_hour;
//converting it into 12 hour format
if (hours>=12)
str="PM";
else
str="AM";
hours=hours>12?hours-12:hours;
//printing the result
if(seconds==sec_prev+1 || (sec_prev==59 && seconds==0))
{
system("CLS");
cout << (hours<10?"0":"") << hours <<":" <<
(minutes<10?"0":"") << minutes << ":" << (seconds<10?"0":"") <<
seconds << " " << str << endl;
}
sec_prev=seconds;
}
return 0;
}
解决方案
如果我必须用一个词来总结它的工作原理,我会说“差”。
标准库已经具有完成大部分工作的功能,因此如果您只想以 12 小时格式打印出当前时间,您可以执行以下操作:
#include <iostream>
#include <iomanip>
#include <ctime>
int main() {
time_t n = std::time(nullptr);
tm now = *localtime(&n);
std::cout << std::put_time(&now, "%H:%M:%S\n");
}
至于循环,大概是继续打印出时间(不断更新),直到你杀死程序。可能作者不知道该告诉编译器说什么:“直到时间结束”,所以他们只使用了“永远”。
关于的if
语句foo<10
似乎要填充前导 0,因此(例如)9 后 8 分钟将打印为9:08
而不是9:8
(但我上面的代码会自动处理)。
作为旁注:在我看来(而且我远非一个人)localtime
设计得相当糟糕。我在上面使用它的方式(立即取消引用它返回的指针,并将其复制tm
到一个新的指针中)有助于最大限度地减少它引起的问题的频率,但如果你有它可用,localtime_r
是首选。
推荐阅读
- django - Django 迁移错误
- python - 如何修复 django 中的错误?
- docker - 在 GCE 中使用 rexray 驱动程序安装 docker 卷失败
- django - 升级 Homebrew 后,如何使用“python manage.py runserver”恢复对本地 Django 站点的访问?
- php - CodeIgniter - 在 CBC 模式下使用 AES 时使用静态 IV
- c++ - C++ SFML:如何成功地迭代渲染形状?
- automated-tests - Appium 或 Xamarin UI 测试 - 经验和缺点
- c# - 重定向 302 循环大概是因为负载平衡和 .NET Core 身份验证
- javascript - 如何向文本框添加动态 ID?
- c# - 如何在 Xamarin.Android 中从 EventHandler 获取值到后台服务