2013-12-08 63 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的回答。)

相关问题