我想在 C++ 中找到日期的周数

I want to find the week number of a date in 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;
}

A struct 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,预计它会失败。