【问题标题】:Validating a date format in c++在 C++ 中验证日期格式
【发布时间】:2017-10-07 01:55:00
【问题描述】:

我正在尝试通过创建流来验证这一行(01 10 2017)上的日期格式。

        if(i%5==4){ //DATE
            std::string date;
            int day;
            int month;
            int year;
            std::ostringstream oss(date);
            oss >> day;
            oss >> month;
            oss >> year;
            if (day >=0 && day <= 31){
                return true;}
            if (month >=01 && month <= 12){
                return true;}
            if (year >=1900){
                return true;}
        }

但是,代码无法编译。我可以做些什么来改进验证?

谢谢

【问题讨论】:

  • 恐怕你颠倒了流插入操作符&lt;&lt;
  • AFAIK std::ostream 没有 operator&gt;&gt;()
  • 可能值得关注std::get_time

标签: c++ date if-statement ostringstream


【解决方案1】:

我可以做些什么来改进验证?

使用经过充分测试的日期/时间库,例如 Howard Hinnant's free, open source, header-only date/time library

bool
is_DMY(const std::string& date)
{
    std::istringstream in{date};
    date::year_month_day ymd;
    in >> date::parse("%d %m %Y", ymd);
    return !in.fail();
}

使用示例:

int
main()
{
    std::cout << is_DMY("30 09 2017") << '\n';
    std::cout << is_DMY("31 09 2017") << '\n';
}

哪个输出:

1
0

这表明 OP 中的第一个测试:

       if (day >=0 && day <= 31){
            return true;}

将提前返回 true 用于“31 09 2017”。 9月只有30天。

【讨论】:

    【解决方案2】:

    希望这会有所帮助。

        if(i%5==4){ //DATE
            std::string date;
            int day;
            int month;
            int year;
            std::ostringstream oss(date);
            oss << day;
            oss << month;
            oss << year;
            const int lookup_table[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
            if (!(month >= 1 && month <= 12)){
                return false;}
            if (!(day >= 1 && day <= lookup_table[month-1])){
                return false;}
            if (!(year >= 1900)){
                return false;}
            return true;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2017-04-04
      • 2010-11-22
      • 2011-01-06
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      相关资源
      最近更新 更多