首页 > 解决方案 > 从上次检查过去的 C++ 天数

问题描述

我想创建一个程序来跟踪用户上次给植物浇水的时间(手动检查)。所以基本上......用户按下一个按钮,程序将今天的日期设置为 date1,然后每天更新 date2。如果差值大于某个日期,则程序返回一个字符串。

int main() {
  int time_elapsed = ; \\???
  std::cout << needs_water(difference) << "\n";
  
}

这里是main函数,调用函数如下:

std::string needs_water(int days) {
  if (days > 3){
    return("Time to water the plant.");
  }
  else {
    return("Don't water the plant!");
  }
}

对不起我的英语不好,提前谢谢。

编辑:简而言之,我想知道的是如何告诉程序从上次检查过去了多少时间。

标签: c++datedate-difference

解决方案


这是一个应该做我理解你想要实现的例子。替换millisecondsdays(c++20) 或替换为hours

#include <iostream>
#include <string>
#include <chrono>
#include <thread>

using namespace std::chrono;
using namespace std::chrono_literals;

template<typename DurationT>
bool time_elapsed(DurationT time) {
  static auto last_check = steady_clock::now();
  auto now = steady_clock::now();
  auto time_passed = now - last_check;
  if (time_passed > time){
    last_check = now;
    return true;
  }
  else {
    return false;
  }
}

int main()
{
    for(int i=0; i < 12; ++i) {
        std::cout << (time_elapsed(milliseconds{3}) ? 
            "Time to water the plant!" : 
            "Don't water the plant!") << std::endl;
        std::this_thread::sleep_for(1ms);
    }
    
    return 0;
}

https://coliru.stacked-crooked.com/a/9e3600759ed902c2


推荐阅读