我使用以下代码将字符串流解析为tm结构:
std::tm tm;
std::stringstream ss("Jan 9 2014 12:35:34");
ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
Run Code Online (Sandbox Code Playgroud)
我有兴趣检查是否发生了解析错误(无效输入).看来这个函数不会抛出异常.没有在文档中找到有用的信息:http: //en.cppreference.com/w/cpp/io/manip/get_time
听起来像'goodbit'可能是方向,但我不知道该怎么做.
(我使用的是VS2013编译器)
与往常一样,std::istream通过设置其中的一个报告错误iostate,这可以使用成员函数被测试fail(),operator!或通过该流对象转换为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';
}
}
Run Code Online (Sandbox Code Playgroud)
如果发生故障,请std::get_time()与std::istreamset一起使用状态标志std::time_get<...>::get_time()。也就是说,您只需要使用
ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
if (!ss) {
// deal with an error
}
Run Code Online (Sandbox Code Playgroud)