簡體   English   中英

運算符>> for boost :: chrono :: duration支持哪些格式?

[英]Which formats are supported by operator>> for boost::chrono::duration?

任何人都可以告訴我從流中讀取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. 如果我正確理解了提升標題,那么一分鍾可以表示為'min'或'minute',一秒可以表示為's'或'second' - 但不是'sec'。 有人能指出我支持的縮寫的一些文檔嗎? (看起來這不是那么直截了當。)

有關持續時間單位的列表,請查看docs duration_units.hpp或查看代碼

"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

在線運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM