我在c ++中使用strptime()函数时遇到问题.
我在stackoverflow中找到了一段代码,如下所示,我想在struct tm上存储字符串时间信息.虽然我应该获得关于我的tm tm_year变量的年份信息,但我总是得到垃圾.有人帮我吗?提前致谢.
string s = dtime;
struct tm timeDate;
memset(&timeDate,0,sizeof(struct tm));
strptime(s.c_str(),"%Y-%m-%d %H:%M", &timeDate);
cout<<timeDate.tm_year<<endl; // in the example below it gives me 113
cout<<timeDate.tm_min<<endl; // it returns garbage
**string s will be like "2013-12-04 15:03"**
Run Code Online (Sandbox Code Playgroud)
Lih*_*ihO 11
cout<<timeDate.tm_year<<endl; // in the example below it gives me 113
Run Code Online (Sandbox Code Playgroud)
它应该给你减少的价值1900所以,如果它给你113它意味着年份2013.月份也将减少1,即如果它给你1,它实际上是二月.只需添加以下值:
#include <iostream>
#include <sstream>
#include <ctime>
int main() {
struct tm tm;
std::string s("2013-12-04 15:03");
if (strptime(s.c_str(), "%Y-%m-%d %H:%M", &tm)) {
int d = tm.tm_mday,
m = tm.tm_mon + 1,
y = tm.tm_year + 1900;
std::cout << y << "-" << m << "-" << d << " "
<< tm.tm_hour << ":" << tm.tm_min;
}
}
Run Code Online (Sandbox Code Playgroud)
输出 2013-12-4 15:3