c – 打印读取时的奇怪行为

c – 打印读取时的奇怪行为,第1张

概述我试图将std :: time_point保存到std :: stream并将其读回.一个问题是使用标准功能’失去’一个小时的某个地方.也就是说,我读的时间比我写的时间少了1个小时.我怀疑我需要在某处设置夏令时.我整理了一个小程序,它将时间打印到std :: stringstream并将其读回. #include <iomanip>#include <iostream>#include <ss 我试图将std :: time_point保存到std :: stream并将其读回.一个问题是使用标准功能’失去’一个小时的某个地方.也就是说,我读的时间比我写的时间少了1个小时.我怀疑我需要在某处设置夏令时.我整理了一个小程序,它将时间打印到std :: stringstream并将其读回.

#include <iomanip>#include <iostream>#include <sstream>#include <chrono>#include <ctime>using std::chrono::system_clock;namespace chrono = std::chrono;voID test();int main(int argc,char** argv){    std::stringstream ss;    auto start = system_clock::Now();    std::time_t ts = system_clock::to_time_t(start);    std::tm time_out = *std::localtime(&ts);    ss << std::put_time(&time_out,"%Y-%m-%d %H:%M:%s %Z") << '\n';    std::cout << ss.str() << std::endl;    std::tm time_in;    ss >> std::get_time(&time_in,"%Y-%m-%d %H:%M:%s %Z");    std::cout << "Are time dsts equal? : " <<    (time_out.tm_isdst == time_in.tm_isdst) << '\n';    std::time_t rawTime = std::mktime(&time_in);    auto end = std::chrono::system_clock::from_time_t(rawTime);    std::cout << "Are time points equal? : " << (start == end) << '\n';    // print the trouble makers    std::time_t start_time = system_clock::to_time_t(start);    std::time_t end_time = system_clock::to_time_t(end);    std::cout << "times: \n"    << '\t' << std::put_time(std::localtime(&start_time),"%c %z") << '\n'    << '\t' << std::put_time(std::localtime(&end_time),"%c %z") << '\n';    // this is a source of strange behavIoUr...//    std::cout << "Difference: "//    << chrono::duration_cast<chrono::seconds>(start - end).count()//    << std::endl;    return 0;}

最奇怪的是该程序打印以下内容:

Are time dsts equal? : 1Are time points equal? : 0times: Tue Dec 11 19:26:24 2012 +0000Tue Dec 11 19:26:24 2012 +0000

当我在程序结束时取消注释3行(打印时间点之间的差异)时,结果是:

Are time dsts equal? : 0Are time points equal? : 0times: Tue Dec 11 19:29:40 2012 +0000Tue Dec 11 18:29:40 2012 +0000Difference: 3600

请注意,dst(夏令时)突然不相等,时间也不同.

我在Mac OS X 10.8.2上使用libc和XCode46-DP2.我使用的铿锵版本是Apple clang 4.1版和clang版本3.2(trunk 167239)

我想我的问题是:
A)至于1小时的差异,这是我的库中的错误还是我没有正确使用标准功能? (后者不会让我感到惊讶……)

B)当我在程序结束时取消注释三行时代码是怎么回事?对我来说这看起来像个错误.有人想在他们的平台上试试吗?

解决方法 我想我们正在查看%Z说明符的错误,也许还有%z说明符,还不确定.

我将更多地研究这些错误的原因.但是,我想继续发布,以便为您提供解决方法.我相信如果您对输入tm进行零初始化,并且始终假设它与您的本地时区相关,那么您将消除您的错误:

std::tm time_in{0};
总结

以上是内存溢出为你收集整理的c – 打印/读取时的奇怪行为全部内容,希望文章能够帮你解决c – 打印/读取时的奇怪行为所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1226415.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存