【问题标题】:How to convert a string Date in format xx/xx/xxxx or x/x/xxxx into integers of day, month & year using Stoi?如何使用 Stoi 将格式为 xx/xx/xxxx 或 x/x/xxxx 的字符串日期转换为日、月和年的整数?
【发布时间】:2019-04-06 04:08:30
【问题描述】:

我正在尝试制定一个函数,它应该采用格式为 xx/xx/xxxx 或 x/x/xxxx 的字符串,并找到所提供字符串的日、月 7 年分量并将它们存储在 数据变量。

我正在考虑使用“std::stoi”,我发现它可以直接用于普通数字,但在约会时使用它时遇到问题。

【问题讨论】:

标签: c++


【解决方案1】:

既然可以使用strptime(),为什么还要重新发明轮子?您只需要小心,因为年份将被记录为自 1900 年以来的年数,并且月份为 0 索引:

std::string date_string; //Assuming you have your date string here
tm tm_date;
char *ret = strptime(date_string.c_str(), "%d/%m/%Y", &tm_date);

if(!ret) {
    std::cout << "ERROR: Bad input date: " << date_string << std::endl;
    return 1; //or however you handle an error
}

std::cout << "You entered date with Year:" << (tm_date.tm_year + 1900)
     << ", Month:" << (tm_date.tm_mon + 1) 
     << ", Day:" << tm_date.tm_mday << std::endl;

在这里运行:ideone

【讨论】:

  • 这是我正在为 Uni 编写的一个程序,但我们不允许使用任何时间/日期标题,因此试图找出使用 stoi 处理它的最佳方法。
  • @RonanW 即使没有 strptime,我仍然不会使用 stoi。我建议研究一下字符串流,因为它们会为您完成大部分解析工作。
猜你喜欢
  • 2022-10-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 2020-06-24
  • 2021-08-14
相关资源
最近更新 更多