fmt:現(xiàn)代的 C++ 字符串格式化庫,實現(xiàn)了 C++20 的特征

fmt 是一個先進(jìn)的文本格式庫,具有現(xiàn)代語言的特征,用來代替 C 的 stdio 和 C++ iostreams。實現(xiàn)了 C++20 的 std::format 標(biāo)準(zhǔn)。fmt 基于 CMakeLists.txt 開發(fā),引入到項目中非常簡單。

通過 FetchContent 引入項目

cmake_minimum_required(VERSION 3.17)
set(CMAKE_CXX_STANDARD 17)
project(fmt-sample)
include(FetchContent)

FetchContent_Declare(fmt
        URL https://github.com/fmtlib/fmt/archive/refs/tags/8.0.1.tar.gz)
FetchContent_MakeAvailable(fmt)

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} fmt)

格式化輸出

#include <fmt/core.h>

int main() {
  fmt::print("Hello, world!\n");
}

格式字符串

std::string s = fmt::format("The answer is {}.", 42);
// s == "The answer is 42."

保留2位小數(shù)

std::string s = fmt::format("The answer is {:.2f}", 1.12345678);
// s == "The answer is 1.12"

使用位置參數(shù)

std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
// s == "I'd rather be happy than right."

使用別名參數(shù)

fmt::print("Hello, {name}! The answer is {number}. Goodbye, {name}.",
           fmt::arg("name", "World"), fmt::arg("number", 42));

時間格式化

#include <fmt/chrono.h>

int main() {
  using namespace std::literals::chrono_literals;
  fmt::print("Default format: {} {}\n", 42s, 100ms);
  fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
}

輸出列表

#include <vector>
#include <fmt/ranges.h>

int main() {
  std::vector<int> v = {1, 2, 3};
  fmt::print("{}\n", v);
}

輸出到文件

#include <fmt/os.h>

int main() {
  auto out = fmt::output_file("guide.txt");
  out.print("Don't {}", "Panic");
}

輸出帶顏色到控制臺

#include <fmt/color.h>

int main() {
  fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
             "Hello, {}!\n", "world");
  fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
             fmt::emphasis::underline, "Hello, {}!\n", "мир");
  fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic,
             "Hello, {}!\n", "世界");
}

測試示例

https://github.com/taoweiji/cpp-cmake-example/tree/master/fmt-sample

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容