【问题标题】:std::get_time - How to check for parsing errorstd::get_time - 如何检查解析错误
【发布时间】:2015-07-28 18:54:11
【问题描述】:

我正在使用以下代码将字符串流解析为 tm 结构:

std::tm tm;
std::stringstream ss("Jan 9 2014 12:35:34");
ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");

我有兴趣检查是否发生解析错误(无效输入)。 这个函数似乎没有抛出异常。 在文档中没有找到有用的信息: http://en.cppreference.com/w/cpp/io/manip/get_time

听起来检查“好位”可能是方向,但我不知道该怎么做。

(我用的是VS2013编译器)

【问题讨论】:

标签: c++ windows


【解决方案1】:

与往常一样,std::istream 通过设置其iostate 之一来报告错误,可以使用成员函数fail()operator!converting the stream object to bool 进行测试。如果要配置流对象,使其在发生错误时抛出异常,可以调用exceptions()

这是一个使用成员函数fail() 来检查是否发生错误的小例子。

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
    std::tm t;
    std::istringstream ss("2011-Februar-18 23:12:34");
    ss >> std::get_time(&t, "%Y-%b-%d %H:%M:%S");
    if (ss.fail()) {
        std::cout << "Parse failed\n";
    } else {
        std::cout << std::put_time(&t, "%c") << '\n';
    }
}

【讨论】:

    【解决方案2】:

    使用std::get_time()std::istream 设置状态标志,以防std::time_get&lt;...&gt;::get_time() 失败。也就是说,您只需使用

    ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
    if (!ss) {
        // deal with an error
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 2015-11-08
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 2017-08-31
      相关资源
      最近更新 更多