简体   繁体   English

为什么此代码在std :: chrono :: system_clock上不起作用?

[英]Why isnt't this code with std::chrono::system_clock working?

I was trying to create a program who tells me what day is tomorrow (starting from 01 Jan) but the code I wrote down doesn't seem to work. 我试图创建一个程序来告诉我明天(从1月1日开始)是星期几,但是我写下的代码似乎无效。

This is my code: 这是我的代码:

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

int main (int argc, char** argv) {
std::chrono::system_clock::time_point today = std::chrono::system_clock::now();

std::tm timeinfo = std::tm();
timeinfo.tm_mon = 0;
timeinfo.tm_mday = 1;
std::time_t tt = std::mktime (&timeinfo);

std::chrono::system_clock::time_point tp = std::chrono::system_clock::from_time_t (tt);


std::chrono::duration<int,std::ratio<60*60*24> >one_day (1);


std::chrono::system_clock::time_point tomorrow = today + one_day;


std::time_t tv;

tt = std::chrono::system_clock::to_time_t ( today );
std::cout << "today is: " << ctime(&tv); 

tt = std::chrono::system_clock::to_time_t ( tomorrow );
std::cout << "tomorrow will be: " << ctime(&tv);

return 0;
}

I'm not getting any error when I compile my code, but when I run my program the output is: 编译代码时没有出现任何错误,但是在运行程序时输出为:

today is: Thu Jan 01 01:00:34 1970 tomorrow will be: Thu Jan 01 01:00:34 1970 今天是:1970年1月1日星期四01970:34明天将是:1970年1月1日星期四01:00:34

Why is it acting this way? 为什么这样做呢?

Thanks everybody! 谢谢大家!

Actually your program is correct. 实际上您的程序是正确的。 You just messed up the output. 您只是弄乱了输出。 The variables used in ctime refer to the (non-initialized) variable tv instead of the variable tt that holds the values you compute from today and tomorrow . ctime使用的变量引用的是(未初始化的)变量tv而不是保存您从todaytomorrow计算的值的变量tt

tt = std::chrono::system_clock::to_time_t ( today );
std::cout << "today is: " << ctime(&tv); 

tt = std::chrono::system_clock::to_time_t ( tomorrow );
std::cout << "tomorrow will be: " << ctime(&tv);

Should be 应该

tt = std::chrono::system_clock::to_time_t ( today );
std::cout << "today is: " << ctime(&tt); 

tt = std::chrono::system_clock::to_time_t ( tomorrow );
std::cout << "tomorrow will be: " << ctime(&tt);

instead. 代替。 After correcting that, it works for me. 更正后,它对我有用。 I now get this output: 我现在得到以下输出:

today is: Sun Jan 31 13:22:30 2016
tomorrow will be: Mon Feb  1 13:22:30 2016

Your variable tv is uninitialized! 您的tv变量未初始化!

See my comments annotating your source code: 查看我的注释您的源代码的注释:

std::time_t tv; // uninitialized

tt = std::chrono::system_clock::to_time_t(today);
std::cout << "today is: " << ctime(&tv); // did you mean tt?

tt = std::chrono::system_clock::to_time_t(tomorrow);
std::cout << "tomorrow will be: " << ctime(&tv); // did you mean tt?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM