2013-12-08 80 views
0

我得到以下錯誤訊息...如下2013年12月8日在C++

錯誤1 錯誤C4996如何輸出日期:「本地時間」:此函數或變量可能是不安全的。考慮使用localtime_s來代替。要禁用折舊,請使用 _CRT_SECURE_NO_WARNINGS

任何幫助,將不勝感激。

const char EOL('\n'); 
    int main()              //draw Xmas tree 
    { 
     time_t now = time(0); 
     tm *ltm = localtime(&now); 



    cout << "Damon Reynolds Tut 1V"<< ltm->tm_mday << " " 
     << 1 + ltm->tm_mon << " " << 1900 + ltm->tm_year;   
     getValidHeigth();            //call procedure 
     cout << EOL;             //then output a new line 
     drawBranches();             //call procedure 
     drawTrunk();             //call procedure 

     cout << EOL;             //then output a new line 
     system("PAUSE");            //hold the screen until a key is pressed 
     return(0); 
    } 
+0

你應該輸出''\ n''爲換行。 – chris

+0

@chris或'std :: endl' – godel9

+0

@ godel9,只有當你需要刷新它時,然後你最好明確地做一個換行符和一個'std :: flush'。 – chris

回答

1

你使用已被更安全的功能取代的功能。但是,如果你能使用C++ 11,可以考慮使用的std ::時辰庫,並使用C++ 11的put_time做格式:

例子:

#include <chrono> 
#include <ctime> 
#include <iomanip> 
#include <iostream> 

int main() 
{ 
    using namespace std::chrono; 

    auto now = system_clock::to_time_t(system_clock::now()); 

    std::cout << std::put_time(std::localtime(&now), "%d %B %Y")... (your code) 
} 

你可能必須使用格式來獲​​得你需要的結果。請參閱put_time參考:http://en.cppreference.com/w/cpp/io/manip/put_time

+0

謝謝你的好東西。 :) –

0

此錯誤是告訴你,你用的是過時的功能,即你正在使用的功能是過時的,你不應該使用它,或者使用更新的版本。這裏的功能是「localtime」。將此函數替換爲「localtime_s」。與非_s版本相比,_s版本具有安全性增強功能。 http://msdn.microsoft.com/en-us/library/a442x3ye.aspx

0

爲了避免過時的功能

this使用率localtime_s 安全增強實現

並格式化你應該做這樣的事情日期:

time_t now = time(0); 
    struct tm ltm; 
    errno_t err = localtime_s(&ltm, &now); 

    const std::string months[] ={ "January", "Febrauary", "March","April", 
           "May","June","July","August","September", 
            "October","November","December"}; 


    std::cout << "Damon Reynolds Tut 1V " 
       << ltm.tm_mday << " " 
     << months[ltm.tm_mon] 
      << " " << 1900 + ltm.tm_year; 
0

如果您使用的函數「更安全」,但更重要的是不能移植到OSX和Linux,微軟寧願選擇它。解決方法在錯誤消息中給出:使用定義的_CRT_SECURE_NO_WARNINGS進行編譯。

的℃溶液格式化時間是strftime,C++的溶液是std::put_time(見polkadotcadaver的回答。)

相關問題