尽管 #include <format>,C++ 命名空间“std”没有成员“format”

End*_*e09 13 c++ fmt visual-studio-2022

我是 C++ 新手。我试图将当前日期和时间存储为字符串变量。

这个问题上,我找到了答案,并安装了该date.h库。

但是,当我尝试使用提供的代码时,遇到了错误:

命名空间“std”没有成员“format”

尽管位于#include <format>脚本的顶部。

我怎样才能解决这个问题?

我正在 Windows 10 上使用 Visual Studio 2022,如果有帮助的话。

这是我的代码:

#include <iostream>
#include <chrono>
#include <date.h>
#include <type_traits>
#include <format>


int main()
{
    std::cout << "The current time is ";
    auto start_time = std::format("{:%F %T}", std::chrono::system_clock::now());
    static_assert(std::is_same_v<decltype(start_time), std::string>{});
    std::cout << start_time << "\n";
}
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 14

std::format被添加到 C++20 标准中的 C++ 中。除非使用 C++20 进行编译,否则不会有std::format.

  • 正如其他答案中所述,使用“ISO C++20 标准 (/std:c++20)”进行编译在 Visual Studio 2022 中不起作用。您需要设置“预览 - 来自最新 C++ 工作草案的功能 (/ std:c++ 最新)”。 (3认同)

Jov*_*bor 10

截至 2021 年 12 月,该功能std::format和其他一些功能仅在Visual Studio 20192022模式C++20下可用。/std:c++latest

\n

这是一个引用:

\n
\n

作为实现 C++20 的一部分,有一些最新发现需要通过标准委员会\nxe2\x80\x99 缺陷报告 (DR) 流程对 ISO C++20 标准进行更改。其中包括这些功能的现有实现(DR 之前)可在\n/std:c++latest 开关下使用。我们\xe2\x80\x99 也在跟踪 DR,并\n在 /std:c++latest 下实施这些问题解决方案。我们的计划是\n在全套标准库 DR 的实现完成后\n在 /std:c++20 开关下提供这些功能。

\n
\n

当 Microsoft 完成所有 DR 的实施后,这些 DRstd::format将在交换机下可用/std:c++20

\n


小智 6

对于遇到此问题的人,请使用 GCC 或 clang。编译器仅部分支持 c++20 中的所有新模块https://en.cppreference.com/w/cpp/compiler_support/20