2011-05-26 6 views
0

HI、ctime()メソッド時間と秒を印刷する方法は?

私は次のコードを持っている:

int main() 
{ 
    time_t rawtime; 

    time (&rawtime); 
    printf ("The current local time is: %s", ctime (&rawtime)); 

    std::string datetoString(ctime (&rawtime)); 
    return 0; 
} 

std::string datetoString (char dat[]) 
        //how to add ctime(&rawtime) in char dat[]? 
{ 
    std::string rez; 
    struct tm; 
    strptime(dat, "%d %b %Y %H:%M:%S", &tm); 
     // what library do i have to inclide for strptime? 

    rez=tm.tm_mday + "-" + tm.tm_mon +"-"+ tm.tm_year+ hour+min+sec; 
           //how to print the hour,minutes and secods? 

return rez; 
} 

を私は私の質問にコメントした場所でエラーを持っています。

+0

このコードはありますか? – Pih

+0

dat []にエラーがあります – marryy

+0

これは宿題です – Blazes

答えて

2

localtime()を使用して、time_t(エポックからの秒数)を分解されたstruct tmインスタンス(またはスレッドセーフであるlocaltime_r)に変換できます。最後に、strftime()を使用して文字列の書式設定を行います。 (どこにでもctimeを使用する必要はありません)。例えば。

 

#include <time.h> 

... 
time (&rawtime); 
struct tm foo; 
struct tm *mytm; 
mytm = localtime_r (&rawtime, &foo); 
char outstr[200]; 
strftime(outstr, sizeof(outstr), "%H:%M:%S", mytm); 
... 
 

エラー処理、潜在的な(些細な)バグの修正、std :: stringへの変換などは、読者の練習として残しました。

関連する問題