7

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"**
4

1 に答える 1

14
cout<<timeDate.tm_year<<endl; // in the example below it gives me 113

それはあなたに減少した値を与えることになっている1900ので、それがあなたに与えた場合、113それは年が2013. 月も だけ減り1ます。つまり、 が表示された場合1、実際には 2 月です。これらの値を追加するだけです:

#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;
    }
}

出力2013-12-4 15:3

于 2013-10-22T17:43:19.570 に答える