2016-02-07 133 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(無效參數) - 所以用戶必須傳遞廢話參數才能看到這一點 - 您不會收到錯誤條件,因爲運行時或操作系統讓您感到意外你的控制,如低內存條件或什麼的。 –