如何在c ++中使用带有指针的localtime_s

问题描述 投票:3回答:1

我正在使用C ++中的函数来帮助获取月份的整数。我进行了一些搜索,发现其中一个使用了本地时间,但是我不想将其设置为删除警告,因此需要使用localtime_s。但是当我使用该指针时,它的指针不再起作用,我需要有人帮助我找到指针所缺少的内容。

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <Windows.h>
#include "FolderTask.h"
#include <ctime> //used for getMonth
#include <string>
#include <fstream>

int getMonth()
{
    struct tm newtime;
    time_t now = time(0);
    tm *ltm = localtime_s(&newtime,&now);
    int Month = 1 + ltm->tm_mon;
    return Month;
}

我得到的错误是:

错误C2440:“正在初始化”:无法从“ errno_t”转换为“ tm *”注意:从整数类型到指针类型的转换需要reinterpret_cast,C样式转换或函数样式转换

c++ pointers localtime
1个回答
8
投票

好像您正在使用Visual C ++,因此localtime_s(&newtime,&now);用所需的数字填充newtime结构。与常规的localtime函数不同,localtime_s返回错误代码。

所以这是该函数的固定版本:

int getMonth()
{
    struct tm newtime;
    time_t now = time(0);
    localtime_s(&newtime, &now);
    int Month = 1 + newtime.tm_mon;
    return Month;
}
© www.soinside.com 2019 - 2024. All rights reserved.