使用 strftime() 时取消“警告:ISO C++11 不支持”

问题描述 投票:0回答:1

所以我目前正在使用 strftime() 以给定格式格式化 tm 对象。我正在尝试使用

strftime(buffer, sizeof(buffer), "%a %d %b %04Y", &timeinfo);

但这在 C++11 中不可用,这不是问题,因为我正在尝试使用 C++17,但是当我使用

进行编译时
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror -Wfatal-errors -c main.cc

我得到这个错误是因为 -Werror

main.cc: In function ‘void print_date(int, int, int, int)’:
main.cc:118:38: error: ISO C++11 does not support the '0' strftime flag [-Werror=format=]
     strftime(buffer, sizeof(buffer), "%a %d %b %04Y", &timeinfo);
                                      ^~~~~~~~~~~~~~~
compilation terminated due to -Wfatal-errors.
cc1plus: all warnings being treated as errors

所以当我删除 -Werror 我收到这个警告

main.cc: In function ‘void print_date(int, int, int, int)’:
main.cc:118:38: warning: ISO C++11 does not support the '0' strftime flag [-Wformat=]
     strftime(buffer, sizeof(buffer), "%a %d %b %04Y", &timeinfo);
                                      ^~~~~~~~~~~~~~~
main.cc:118:38: warning: ISO C++11 does not support field width in strftime format [-Wformat=]

但是有办法抑制这个警告吗?老实说,如果我使用 -std=c++17 编译 main.cc,我什至不明白为什么会出现此错误。

当我执行 g++ --version 它输出时,这与我的 g++ 版本有关吗

g++ (GCC) 8.5.0 20210514 (Red Hat 8.5.0-16)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
c++ c++11 c++17 suppress-warnings strftime
1个回答
1
投票

警告“警告:ISO C++11 不支持 strftime 格式的字段宽度”是这里的关键。

%04Y
是荒谬的。只需使用
%Y
already 表示“使用完整的年份”(
%y
是两位数的截断形式)。
strftime
不是
printf
,它有自己的格式化语言
,而
%04Y
不是它能理解的东西。

是的,从技术上讲,这意味着 1000 年之前的日期将少于四位数。如果您需要处理它们,并将它们补零到四位数字,您将不得不混合使用

strftime
和常规字符串格式。

© www.soinside.com 2019 - 2024. All rights reserved.