Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::get_time - How to check for parsing error

Tags:

c++

windows

I am using the following code to parse a stringstream into 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");

I am interested to check whether parsing error has occured (invalid input). It seems that this function does not throws an exception. did not find usefull information in the documentation: http://en.cppreference.com/w/cpp/io/manip/get_time

Sounds like checking the 'goodbit' may be the direction, but I am not sure how to do it.

(I am using VS2013 compiler)

like image 849
Yan4321 Avatar asked May 17 '15 04:05

Yan4321


1 Answers

As always, std::istream reports error by setting one of its iostate, which can be tested using the member function fail(), operator!, or by converting the stream object to bool. If you want to config the stream object so that it throws an exception when an error occurs, you can call exceptions().

Here's a small example that uses the member function fail() to check if an error has occurred.

#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';
    }
}
like image 174
cpplearner Avatar answered Nov 06 '22 03:11

cpplearner