【问题标题】:localtime c++ not working as I would like tolocaltime c++ 无法正常工作
【发布时间】:2020-08-01 23:38:15
【问题描述】:

我在 C++ 中遇到了本地时间问题。我使用 vs 代码和 localtime_s 不工作。当我使用本地时间时,它会为今天的小时、分钟和秒提供非常大的数字(如“6417576:16480216:6422248”)。例如,如何将其更改为“16:30:30”之类的内容?我找不到任何对我有帮助的信息,所以也许你们会的。 这是我的代码:

void write(string team_name)
    {
        //current time
        time_t current;
        current=time(0);
        struct tm now;
        localtime(&current);
        stringstream time;
        time<<now.tm_hour<<":"<<now.tm_min<<":"<<now.tm_sec;
        //writing filenames and times
        stringstream filename;
        filename<<"Filename"<<"_"<<team_name<<time.str()<<".txt";
        ofstream file;
        file.open(filename.str());
        file<<show();
        void print_time();
        file.close();
    }
};

【问题讨论】:

标签: c++ localtime


【解决方案1】:

这两个语句没有任何联系:

struct tm now;
localtime(&current);

第二条语句解决了所有问题,但丢弃结果,因此now 中的所有字段仍设置为创建变量时的任意值。

localtime 函数返回一个指向结构的指针,所以你应该使用它:

struct tm *now = localtime(&current);
// use now->something

【讨论】:

    猜你喜欢
    • 2011-08-31
    • 2013-08-26
    • 2010-11-29
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多