首页 > 解决方案 > 我想在 C++ 中找到日期的周数

问题描述

我试图找出 C++ 中日期的周数。我将控制台中的日期作为字符串并将其划分为日期、月份和年份。

这是我的代码。请帮我找出问题所在。

#include <iostream> 
using namespace std;
#include <string>
#include <cstring>
#include <ctime>
int main(void)
{
  struct tm tm;
  char timebuf[64];
  memset(&tm, 0, sizeof tm);
  string date;
  cout<<"Enter the date (dd-mm-yyyy) : "; //print statement is used to print message on console
  cin>>date; //taking input from user
  int day=stoi(date.substr(0,2));
  int month=stoi(date.substr(3,2));
  int year=stoi(date.substr(6,4));
  //cout << day << month << year << endl;
  tm.tm_sec = 0;
  tm.tm_min = 0;
  tm.tm_hour = 23;
  tm.tm_mday = day;
  tm.tm_mon = month;
  tm.tm_year = year;
  tm.tm_isdst = -1;
  mktime(&tm);

  if (strftime(timebuf, sizeof timebuf, "%W", &tm) != 0) {
    printf("Week number is: %s\n", timebuf);
  }

  return 0;
}

标签: c++dateweek-number

解决方案


Astruct tm使用从 0 开始的月份编号。当您的用户输入04-11-2020时,他们(大概)表示 2020 年 11 月 4 日。当您将数据放入 时struct tm,您需要从月份数中减去 1。

年份也从 1900 开始,因此您需要从年份编号中减去 1900。

或者,您可以使用std::get_time为您读取和解析字段:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>

int main() {    
    std::tm then{};

    std::istringstream in("04-11-2020");

    if (!(in >> std::get_time(&then, "%d-%m-%Y")))
        std::cerr << "Conversion failed\n";

    mktime(&then);

    // %W for 0-based, %V for 1-based (ISO) week number:
    std::cout << std::put_time(&then, "%V\n");
}

std::get_time知道如何将人类可读的日期转换为所需的数字范围tm,因此您不必以tm这种方式明确考虑变幻莫测(是的,至少对我而言,这会产生45,正如预期的那样)。但是有一个警告:std::get_time需要零填充字段,因此(例如)如果您使用4-11-2020而不是04-11-2020,则预计它会失败。


推荐阅读