2016-02-07 130 views
1

我正在使用C++中的函数来获取月份的整数。我做了一些搜索,发现一个使用本地时间,但我不想设置它来删除警告,所以我需要使用localtime_s。但是当我使用它时,我的指针不再起作用,我需要有人帮助我找到我缺少的指针。如何在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样式转换或函数样式转换

+0

请[阅读有关如何提出好的问题(http://stackoverflow.com/help/how-to-ask)。您还应该学习如何创建[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。你是否使用Windows ['localtime_s'](https://msdn.microsoft.com/en-us/library/a442x3ye.aspx)函数或['localtime_s'](http://en.cppreference。 com/w/c/chrono/localtime)从C标准库?这两个是不同的。请详细说明您遇到的问题,请向我们展示您在构建时可能遇到的错误消息。 *精心制作!* –

+0

因此,您使用的是[Windows Visual Studio扩展'localtime_s'](https://msdn.microsoft.com/en-us/library/a442x3ye.aspx)。阅读参考资料,检查并阅读函数返回的内容, –

回答

3

它看起来像你使用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; 
} 
+0

谢谢,这正是我所需要的。我并不相信带有所需信息的指针变成了新时间,并且无法理解这一点。 –

+0

如果你忽略了错误结果,你可能不会打扰'_s'版本。 – hvd

+0

非_s版本返回一个指向C运行时静态缓冲区的指针,这有点糟糕。但是,凯文使用它的主要原因是为了摆脱MSVC的弃用警告而不用担心'_CRT_SECURE_NO_DEPRECATE'的定义。无论如何,localtime_s永远返回的唯一错误条件是EINVAL(无效参数) - 所以用户必须传递废话参数才能看到这一点 - 您不会收到错误条件,因为运行时或操作系统让您感到意外你的控制,如低内存条件或什么的。 –