2010-06-07 128 views
1

此刻,我正在尝试读取格式化的时间字符串,并从中创建持续时间。我目前正在尝试使用boost date_time time_duration类来读取和存储该值。将时间字符串转换为持续时间

boost date_time提供了一种方法time_duration duration_from_string(std::string),该方法允许从时间字符串创建time_duration,并接受适当格式化的字符串("[-]h[h][:mm][:ss][.fff]".)。

现在,如果使用格式正确的时间字符串,此方法可以正常工作。但是,如果您提交的内容如“ham_sandwich”或“100”等无效,则会返回无效的time_duration。特别是如果您尝试将其传递到标准输出流,则会发生断言。

我的问题是:有谁知道如何测试boost time_duration的有效性?如果失败了,你能否提出另一种读取时间字符串并从中获取持续时间的方法?

注:我已经尝试了time_duration提供的明显测试方法; is_not_a_date_time(),is_special()等,他们不认为有问题。

使用升压1.38.0

回答

4

从文档,它看起来像你可能想使用流运营商(operator<<operator>>)尝试;错误条件描述在Date Time Input/Output

或者,我想你可以在传递字符串之前验证字符串。右手,它看起来并不像那个特定的方法有任何错误处理。

编辑: 我不知道我还以为来检查这样的返回值,如果不是因为Brian的答案,但对于这里的完整性是一个完整的例子,以一个字符串作为输入。您可以检查返回值或让它抛出异常(我相信您会想要赶上std::ios_base_failure):

#include <iostream> 
#include <sstream> 
#include <string> 
#include <boost/date_time/posix_time/posix_time.hpp> 

using namespace std; 
using namespace boost::posix_time; 

int main(int argc, char **argv) { 
    if (argc < 2) { 
     cout << "Usage: " << argv[0] << " TIME_DURATION" << endl; 
     return 2; 
    } 

    // No exception 
    stringstream ss_noexcept(argv[1]); 
    time_duration td1; 
    if (ss_noexcept >> td1) { 
     cout << "Valid time duration: " << td1 << endl; 
    } else { 
     cout << "Invalid time duration." << endl; 
    } 

    // Throws exception 
    stringstream ss2; 
    time_duration td2; 
    ss2.exceptions(ios_base::failbit); 
    ss2.str(argv[1]); 
    try { 
     ss2 >> td2; 
     cout << "Time duration: " << td2 << endl; 
    } catch (ios_base::failure e) { 
     cout << "Invalid time duration (exception caught). what():\n" 
       << e.what() << endl; 
    } 
} 
+0

我已经使用了错误条件实际上是尝试,但问题是,断言发生在TIME_DURATION内部,也不要紧,关于流的错误状态设置 具体是什么错误条件允许你do是设置其ios :: failbit时抛出的流。所以在我的情况下,断言发生在time_duration内部,然后流检测到错误。 – radman 2010-06-07 02:04:31

+0

嗯......让我把一些示例代码放在一起,看看我能否看到问题。 – 2010-06-07 02:12:23

+0

对我很好。 :) – 2010-06-07 03:11:49

2

使用流操作符。

time_duration td; 
if (std::cin >> td) 
{ 
    // it's valid 
} 
else 
{ 
    // it isn't valid 
} 
+0

Brian你实际上首先得到了答案(使用流操作符来构建time_duration而不是使用duration_from_string)。我正在给Sam打勾,因为他的回答更全面和详细。但是如果我可以多次投票给你! – radman 2010-06-07 03:37:33

+0

我会为你做。谢谢,Brian,指针。 – 2010-06-07 04:08:20