You need to enable JavaScript to run this app. C++使用fmt库指定输出宽度时如何仅给文本内容添加下划线
优惠活动
大模型
产品
解决方案
定价
更多

C++使用fmt库指定输出宽度时如何仅给文本内容添加下划线

问题原因

你当前是将下划线样式设置为了fmt::print的全局样式,整个输出字符串(包括宽度对齐产生的填充空格)都处于样式作用范围内,因此空格也会被添加下划线效果。

解决方法

不要全局添加下划线样式,改用fmt::styled单独为每个实际文本内容包裹下划线样式,填充空格会自动放在样式作用范围之外,不会带下划线。

示例代码

#include <fmt/core.h>
#include <fmt/color.h>
int main() {
    fmt::print("{:<22}{:<8}{}\n", 
        fmt::styled("Last Write Time", fmt::emphasis::underline),
        fmt::styled("Size", fmt::emphasis::underline),
        fmt::styled("Name", fmt::emphasis::underline)
    );
}

可选优化

如果需要频繁使用下划线样式,可以封装一个工具函数简化代码:

template <typename T>
auto underlined(T&& content) {
    return fmt::styled(std::forward<T>(content), fmt::emphasis::underline);
}

// 调用示例
fmt::print("{:<22}{:<8}{}\n", 
    underlined("Last Write Time"),
    underlined("Size"),
    underlined("Name")
);

内容的提问来源于stack exchange,提问作者Haoshen Zhong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 22:42:02