簡體   English   中英

我想在 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;
}

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 ,預計它會失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM