c++ - operator>> 的 boost::chrono::duration 支持哪些格式?

标签 c++ boost c++-chrono

谁能告诉我从流中读取 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 header ,一分钟可以表示为“min”或“minute”,一秒可以表示为“s”或“second”,但不能表示为“sec”。任何人都可以指出一些支持缩写的文档吗? (看起来这不是那么简单。)

最佳答案

有关持续时间单位列表,请查看文档 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

关于c++ - operator>> 的 boost::chrono::duration 支持哪些格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34102284/

相关文章:

c++ - boost::compute 是否支持 const 修饰符?

c++ - 将当前日期精确到毫秒

c++ - Direct2D 深度缓冲区

c++ - vim 中意外的红色括号突出显示

c++ - 为 shared_ptr<MyClass> 的 vector move 构造函数

c++ - 使用 std::chrono/date::gps_clock 将双 gps 时间戳转换为 utc/tai

c++ - 计时库中的计数时间点

c++ - 变量 'equation' 周围的堆栈已损坏

c++ - 在编译时创建 N 个对象的最佳方式

c++ - boost 、几何