首页 > 解决方案 > localtime c++ 无法正常工作

问题描述

我在 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

解决方案


没有任何东西以任何方式连接这两个语句:

struct tm now;
localtime(&current);

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

localtime函数返回一个指向结构的指针,因此您应该使用它:

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

推荐阅读