【问题标题】:converting a timestring to a duration将时间字符串转换为持续时间
【发布时间】:2010-06-07 01:38:51
【问题描述】:

目前我正在尝试读取格式化的时间字符串并从中创建持续时间。我目前正在尝试使用 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() 等,他们没有发现有问题。

使用 boost 1.38.0

【问题讨论】:

    标签: c++ boost datetime


    【解决方案1】:

    从文档看来,您可能想尝试使用流运算符(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;
        }
    }
    

    【讨论】:

    • 我实际上已经尝试过使用错误条件,但问题是断言发生在 time_duration 内,因此设置流上的错误条件并不重要具体来说,错误条件允许你做什么做的是设置它的 ios::failbit 时流会抛出。因此,在我的情况下,断言发生在流检测到错误之前的 time_duration 内。
    • 嗯...让我把一些示例代码放在一起,看看我是否能看到问题。
    • 是的,成功了。我不知道您可以使用流运算符来创建 time_duration 但这绝对是正确的方法。感谢您的帮助。
    【解决方案2】:

    使用流操作符。

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

    【讨论】:

    • Brian 您实际上首先得到了答案(使用流运算符构建 time_duration 而不是使用 duration_from_string)。我给 Sam 打勾,因为他的回答更加全面和详细。但是,如果我能多次投票给你,我会的!
    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2016-02-03
    • 1970-01-01
    • 2021-01-11
    相关资源
    最近更新 更多