Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 获取时间-如何检查解析错误_C++_Windows - Fatal编程技术网

C++ 获取时间-如何检查解析错误

C++ 获取时间-如何检查解析错误,c++,windows,C++,Windows,我使用以下代码将stringstream解析为tm struct: std::tm tm; std::stringstream ss("Jan 9 2014 12:35:34"); ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S"); 我想检查是否发生了解析错误(输入无效)。 这个函数似乎没有抛出异常。 在文档中未找到有用的信息: 听起来,检查“goodbit”可能是一个方向,但我不确定如何做 (我正在使用VS2013编译器)使用s

我使用以下代码将stringstream解析为tm struct:

std::tm tm;
std::stringstream ss("Jan 9 2014 12:35:34");
ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
我想检查是否发生了解析错误(输入无效)。 这个函数似乎没有抛出异常。 在文档中未找到有用的信息:

听起来,检查“goodbit”可能是一个方向,但我不确定如何做

(我正在使用VS2013编译器)

使用
std::get_time()
std::istream
设置状态标志,以防
std::time\u get::get_time()
失败。也就是说,你只要使用

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

与往常一样,
std::istream
通过设置一个its来报告错误,该its可以使用成员函数进行测试,也可以通过。如果您希望配置流对象,使其在发生错误时抛出异常,则可以调用

下面是一个小示例,它使用成员函数
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';
    }
}
#包括
#包括
#包括
int main()
{
std::tmt;
标准:istringstream ss(“2011-Februar-1823:12:34”);
标准::获取时间(&t),%Y-%b-%d%H:%M:%S);
if(ss.fail()){

std::我是否可以尝试在上阅读示例,但由于模板地狱,我的眼睛开始流血。@wcochran,你并不孤单:/