2011-08-18 100 views
2

我試圖將諸如「2011年8月12日」之類的字符串轉換爲time_t或經過的秒數,或者我可以用它來比較日期列表。C++將字符串轉換爲time_t問題

此刻,我嘗試了以下,但輸出似乎等於假!另外,過去的秒數似乎在不斷變化?

這是正確的嗎?

#include <iostream> 
#include <string> 
#include <cstdlib> 
#include <cstring> 
#include <time.h> 
#include <stdio.h> 

using namespace std; 

int main() 
{ 

    struct tm tmlol, tmloltwo; 
    time_t t, u; 

    t = mktime(&tmlol); 
    u = mktime(&tmloltwo); 
    //char test[] = "01/01/2008";string test = "01/01/2008"; 

    strptime("10 February 2010", "%d %b %Y", &tmlol); 
    strptime("10 February 2010", "%d %b %Y", &tmloltwo); 

    t = mktime(&tmlol); 
    u = mktime(&tmloltwo); 

    cout << t << endl; 
    cout << u << endl; 

    if (u>t) 
    { 
     cout << "true" << endl; 
    } 
    else if (u==t) 
    { 
     cout << "same" << endl; 
    } 
    else 
    { 
     cout << "false" << endl; 
    } 

    cout << (u-t); 
} 

回答

8

您應該在使用前初始化結構。試試這個:

#include <iostream> 
#include <string> 
#include <cstdlib> 
#include <cstring> 
#include <time.h> 
#include <stdio.h>   

using namespace std; 

int main() 
{ 
    struct tm tmlol, tmloltwo; 
    time_t t, u; 

    // initialize declared structs 
    memset(&tmlol, 0, sizeof(struct tm)); 
    memset(&tmloltwo, 0, sizeof(struct tm)); 

    strptime("10 February 2010", "%d %b %Y", &tmlol);   
    strptime("10 February 2010", "%d %b %Y", &tmloltwo); 

    t = mktime(&tmlol); 
    u = mktime(&tmloltwo); 

    cout << t << endl; 
    cout << u << endl; 

    if (u>t) 
    { 
     cout << "true" << endl; 
    } 
    else if (u==t) 
    { 
     cout << "same" << endl; 
    } 
    else 
    { 
     cout << "false" << endl; 
    } 

    cout << (u-t) << endl; 

    return 0; 
} 
+0

簡單:'struct tm tmlol = {0}; struct tm tmloltwo = {0};'。 (海灣合作委員會可能會警告缺少初始值設定項;隨意忽略它。) –

+0

@Keith:Simpler:'tm tmlol = {},tmloltwo = {};'; - ] – ildjarn

+0

@ildjarn:有趣的。這在C中是非法的;我不知道C++允許它。 –