gpt4 book ai didi

c++ - 如何使用 gmtime 和 asctime 删除警告 C4996

转载 作者:行者123 更新时间:2023-11-28 06:58:23 26 4
gpt4 key购买 nike

我的 C++ 项目中有 4 级警告 我想解决它 警告是

Warning 1 warning C4996: 'gmtime': This function or variable may be unsafe. Consider using gmtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Warning 2 warning C4996: 'asctime': This function or variable may be unsafe. Consider using asctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

C++ 代码

time_t ltime;
time(&ltime);
tm* gmt = gmtime(&ltime);

char* asctime_remove_nl = asctime(gmt);

最佳答案

下面的函数返回指向静态对象的指针,这些对象可能会被其他后续调用覆盖(K&R Book)。因此它们不被认为是安全的,并且由于这个 VS 编译器会给出警告/错误。可以通过在项目(.proj 文件)中添加 MACRO (CRT_SECURE_NO_WARNINGS) 来将其删除。

gmtime()
asctime()

但是,我们可以编写小的实用函数来复制这些静态字符串。

// This would return the copy of time/date in std::string object to caller
std::string get_gmtime_asctime() {
time_t ltime;
time(&ltime);
struct tm* gt = ::gmtime(&ltime);
char* tmp = ::asctime(gt);
std::string output(tmp);
return output;
}

int main() {
std::string out = get_gmtime_asctime();
std::cout<<out<<std::endl;

}

关于c++ - 如何使用 gmtime 和 asctime 删除警告 C4996,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22871770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com