【问题标题】:std::chrono::from_stream correct usagestd::chrono::from_stream 正确用法
【发布时间】:2019-10-10 01:55:43
【问题描述】:

我正在考虑使用函数std::chrono::from_stream (std::chrono::year_month_day)const std::string& 获取std::chrono::year_month_day 对象,例如2018-12-09T00:00:00

在 cppreference 中没有使用 std::chrono::from_stream 的示例。所以我想,它可以像std::get_time 一样使用。

但有一个问题。 std::chrono::year_month_day 有很奇怪的参数(个人意见)

(std::basic_istream<CharT, Traits>& is, const CharT* fmt, std::chrono::year_month_day& ymd, std::basic_string<CharT, Traits, Alloc>* abbrev = nullptr, std::chrono::minutes* offset = nullptr)

又不知什么原因返回std::basic_istream,才发现自己真的不知道如何正确使用。

请问有人知道吗? 谢谢。

【问题讨论】:

    标签: c++ std chrono c++20


    【解决方案1】:

    首先,from_stream 适用于流,而不是字符串。如果要使用字符串,则必须先通过流:

    std::istringstream iss("2018-12-09T00:00:00");
    

    现在你期待的函数实际上是parse,而不是from_stream。它与get_time 等其他操纵器一样工作,并将其工作委托给from_stream

    std::chrono::year_month_day date;
    if (not (iss >> std::chrono::parse("%FT%T", date))) {
        // Handle error
    }
    

    这相当于from_stream(iss, "%FT%T", date)

    您可以在Howard's CppCon talk on time zones 中看到一些解析的用法。他继续展示使用额外参数来确定实际解析的时区缩写和偏移量的示例,但这与您问题中的用例无关。 (霍华德是该库的作者,也是推动其标准化的人。)

    【讨论】:

      【解决方案2】:

      这并不奇怪。

      const std::string in = "2018-12-09T00:00:00";
      std::stringstream ss(in);
      
      std::chrono::year_month_day ymd;
      
      if (std::chrono::from_stream(ss, "%FT%T", ymd))
      {
          std::cout << "Date: " << ymd << '\n';
      }
      

      (遗憾的是,我们还不能 demo 这个,因为 libstd++ doesn't implement P0355libc++'s nascent support is insufficient。)

      注意这个提供了年/月/日,所以必须舍弃时间。

      您可能希望考虑其他一些from_stream 重载(例如可能是this one)。

      【讨论】:

      • 哦,我明白了,为什么它返回 basic_istream。
      • @PřemyslŠťastný 是的,就像您习惯的插入/提取运算符一样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      相关资源
      最近更新 更多