I'm solving a problem on a site. My code is the following:
string timeConversion(string s) {
std::tm t = {};
string result = "";
std::istringstream ss(s);
ss >> std::get_time(&t, "%I:%M:%S%p");
if (ss.fail()) {
std::ostringstream oss;
oss << std::put_time(&t, "%H:%M:%S") << endl;
result = oss.str();
} else {
result = "Parse failed";
}
return result;
}
When I input 07:05:45PM it returns 07:05:45. But I expect 19:05:45. What is wrong?
UPDATE
The code is wrong for "if" statement. It must be
string timeConversion(string s) {
std::tm t = {};
string result = "";
std::istringstream ss(s);
ss >> std::get_time(&t, "%I:%M:%S%p");
if (ss.fail()) {
result = "Parse failed";
} else {
std::ostringstream oss;
oss << std::put_time(&t, "%H:%M:%S") << endl;
result = oss.str();
}
return result;
}
The code returns "Parse failed" for "07:05:45PM" (g++ 5.4.0) It's unexpected too.