c++ - 我想在 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;
}
解决方案
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
,则预计它会失败。
推荐阅读
- java - Java 一行中的多个数字
- java - Process.waitFor() 不等待查询完成
- html - 如何处理我的 Multer 意外错误?
- javascript - 每当数组中有一个项目在我的 React 项目中无法正常工作时显示数组内容
- php - CakePHP:随机查询一个结果,排除两个值
- r - 如何使用随机样本在 R 上创建 Stan 模型
- javascript - 当我将元素添加到购物车时,它添加了两个元素,而不仅仅是一个我该如何更正它?
- github - ArgoCD 私有回购声明式方法
- yarnpkg - 纱线构建有问题:生产
- python - 如果传递了另一个参数,则 Python 函数使参数成为强制性参数