在C ++中验证出生日期

普里扬卡

我刚刚开始学习C ++。在浏览此站点上的代码时,我遇到了一个验证用户输入日期的代码,但是问题在于它甚至可以包含将来的值,因此需要对该逻辑进行调整才能工作以接受DOB。因此,我决定使用“ time()”函数获取当前时间,然后将其与输入的日期进行比较。首先,我在代码中添加了两行(在下面的代码中注释的行),它们分别是

time(&tNow);

const struct tm *now = localtime(&tNow);

这是我的代码:

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

using namespace std;
// function expects the string in format dd/mm/yyyy:
bool extractDate(const std::string& s, int& d, int& m, int& y){
    std::istringstream is(s);
    char delimiter;
    if (is >> d >> delimiter >> m >> delimiter >> y) {
        struct tm t = {0};
        t.tm_mday = d;
        t.tm_mon = m - 1;
        t.tm_year = y - 1900;
        t.tm_isdst = -1;

        // normalize:
        time_t when = mktime(&t);

        time_t tNow;

      //   time(&tNow);

          const struct tm *norm = localtime(&when);

      //  const struct tm *now = localtime(&tNow);       /* when I uncomment this line the code                              
      //                                                   does not accept future date   */



      // validate (is the normalized date still the same?):   
        return (norm->tm_mday == d    &&
                norm->tm_mon  == m - 1 &&
                norm->tm_year == y - 1900);
    }
    return false;
}


int main() {

    std::string s("11/01/2015");
    int d,m,y;

    if (extractDate(s, d, m, y))
        std::cout << "date " 
                  << d << "/" << m << "/" << y
                  << " is valid" << std::endl;
    else
        std::cout << "date is invalid" << std::endl;
}

当我取消注释时,const struct tm *now = localtime(&tNow);代码会为任何将来的日期值提供正确的输出作为“无效日期” ...但是为什么会这样。我得到正确的输出,但是我想知道为什么。

马特·彼得森(Mats Petersson)

好的,所以问题在于,localtime当您多次调用它时,它返回相同的缓冲区。您需要复制结果(或使用localtime_r带有额外参数的参数,但它不那么可移植)。

这是我的代码调试会话(带有未注释的部分):

(gdb) p norm 
$1 = (const tm *) 0x7ffff75aca60 <_tmbuf>
(gdb) p now
$2 = (const tm *) 0x7ffff75aca60 <_tmbuf>

我解决的方法是这样的:

  const struct tm norm = *localtime(&when);

  const struct tm now = *localtime(&tNow);


  // validate (is the normalized date still the same?):   
  return (norm.tm_mday == d    &&
      norm.tm_mon  == m - 1 &&
      norm.tm_year == y - 1900);

在同一主题上还有其他几种变体,但这应该可以工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章