【问题标题】:Which formats are supported by operator>> for boost::chrono::duration?对于 boost::chrono::duration,operator>> 支持哪些格式?
【发布时间】:2015-12-05 07:06:51
【问题描述】:

谁能告诉我从流中读取boost::chrono::duration 时支持哪些格式?我没有找到任何关于此的文档。 我阅读了标题并从那里获得了一些信息 - 但我并不完全理解它。

一个非常小的测试程序:

#define BOOST_CHRONO_VERSION 2
#include <boost/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>
#include <iostream>

#include <chrono>

using namespace boost::chrono;

int main() {
  boost::chrono::seconds tp1;
  std::cin >> tp1;
  std::cout << symbol_format << tp1 << std::endl;
}

当我在适当的标题中找到一些单位时,它运作良好:

$ echo "4 seconds" | ./a.out 
4 s
$ echo "6 minutes" | ./a.out 
360 s
$ echo "2 h" | ./a.out 
7200 s

我想要做的,是一些组合的方法——这是行不通的:

1 minute 30 seconds
1:30 minutes
1.5 minutes
2 h 6 min 24 seconds

对我来说,解析在第一个单元之后直接停止。我尝试了一些不同的分隔符(如':'、','、...)但没有成功。

两个问题:

  1. 这种组合/扩展的传入boost::chrono::duration 可能吗?如果有,怎么做?
  2. 如果我正确理解了 boost 标头,一分钟可以表示为“min”或“minute”,一秒可以表示为“s”或“second”,但不能表示为“sec”。谁能指出我支持的缩写的一些文档? (看起来这不是那么简单。)

【问题讨论】:

    标签: c++ boost chrono


    【解决方案1】:

    有关持续时间单位的列表,请查看文档duration_units.hpp 或查看code

    "s" / "second" / "seconds" 
    "min" / "minute" / "minutes"
    "h" / "hour" / > "hours"
    

    如果您需要解析多个持续时间条目,您可以编写类似parse_time 的函数:

    #define BOOST_CHRONO_HEADER_ONLY
    #define BOOST_CHRONO_VERSION 2
    
    #include <iostream>
    #include <boost/chrono.hpp>
    #include <boost/algorithm/string.hpp>
    #include <sstream>
    #include <algorithm>
    #include <stdexcept>
    
    using namespace std;
    using namespace boost;
    using namespace boost::chrono;
    
    seconds parse_time(const string& str) {
      auto first = make_split_iterator(str, token_finder(algorithm::is_any_of(",")));
      auto last = algorithm::split_iterator<string::const_iterator>{};
    
      return accumulate(first, last, seconds{0}, [](const seconds& acc, const iterator_range<string::const_iterator>& r) {
        stringstream ss(string(r.begin(), r.end()));
        seconds d;
        ss >> d;
        if(!ss) {
          throw std::runtime_error("invalid duration");
        }
        return acc + d;
      });
    }
    
    int main() {
      string str1 = "5 minutes, 15 seconds";
      cout << parse_time(str1) << endl; // 315 seconds
    
      string str2 = "1 h, 5 min, 30 s";
      cout << parse_time(str2) << endl; // 3930 seconds
    
      try {
        string str3 = "5 m";
        cout << parse_time(str3) << endl; // throws
      } catch(const runtime_error& ex) {
        cout << ex.what() << endl;
      }
    
      return 0;
    }
    

    parse_time 在分隔符 , 上拆分并处理单独的持续时间。如果发生错误,它会抛出runtime_error

    Run it online

    【讨论】:

    • 感谢您的想法。为我的实现更改了几件事,例如使用模板。还决定使用空格作为分隔符:例如'2h 30min' 是有效的持续时间规范。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2019-07-16
    • 2012-12-14
    • 2015-08-05
    • 2014-08-04
    相关资源
    最近更新 更多