我正在尝试创建一个程序,告诉我明天会是哪一天(从1月1日开始),但我写下的代码似乎不起作用。
这是我的代码:
#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;
}
编译代码时我没有收到任何错误,但是当我运行程序时,输出是:
今天是:Thu Jan 01 01:00:34 1970 明天将是:Thu Jan 01 01:00:34 1970
为什么这样做?
谢谢大家!
答案 0 :(得分:3)
实际上你的程序是正确的。你刚搞砸了输出。 ctime
中使用的变量指的是(非初始化的)变量tv
,而不是包含您从tt
和today
计算的值的变量tomorrow
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);
应该是
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);
代替。在纠正之后,它对我有用。我现在得到这个输出:
today is: Sun Jan 31 13:22:30 2016
tomorrow will be: Mon Feb 1 13:22:30 2016
答案 1 :(得分:2)
您的变量tv
未初始化!
请参阅我的注释源代码注释:
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?