What is the usage of the strptime function in C++?
In C++, the strptime function is used to parse a date and time string into a tm structure, with the following prototype:
char *strptime(const char *buf, const char *format, struct tm *tm);
Explanation of parameters:
- buf: a C string that contains a date and time string
- the format of the date and time string
- tm: a pointer to a tm structure, used to store parsed date and time information.
Function return value:
- Return a pointer to the unparsed portion of the string buf if the parsing is successful.
- Return NULL if the parsing fails.
He was so tired that he could barely keep his eyes open.
Option: He was so exhausted that he could hardly keep his eyes from closing.
#include <iostream>
#include <ctime>
int main() {
const char *dateStr = "2022-01-01 12:30:45";
struct tm tm;
char *endPtr = strptime(dateStr, "%Y-%m-%d %H:%M:%S", &tm);
if (endPtr != NULL) {
std::cout << "Year: " << tm.tm_year + 1900 << std::endl;
std::cout << "Month: " << tm.tm_mon + 1 << std::endl;
std::cout << "Day: " << tm.tm_mday << std::endl;
std::cout << "Hour: " << tm.tm_hour << std::endl;
std::cout << "Minute: " << tm.tm_min << std::endl;
std::cout << "Second: " << tm.tm_sec << std::endl;
} else {
std::cout << "Parsing failed." << std::endl;
}
return 0;
}
In the example above, we used the strptime function to parse the date and time string “2022-01-01 12:30:45” according to the format “%Y-%m-%d %H:%M:%S” and stored the parsed date and time information in the tm structure. Then we output the parsed year, month, day, hour, minute, and second information.