C++ C+中的粗体输出+;

C++ C+中的粗体输出+;,c++,string,C++,String,我正在编写一本词典,当我打印(输出)单词defensions时,我想用粗体打印单词本身。 当我打印时 cout<<word<<endl<<defention1<<defenition2<<endl; Cuth标准C++使用各种区域/字符集显示各种字母表中的输出。但是,文本本身就是文本,没有格式 如果希望输出为彩色,或粗体,或斜体,则需要向终端发送适当的字符代码 但是,这是实现定义的,不保证在所有平台上都能工作 例如,在Linux/U

我正在编写一本词典,当我打印(输出)单词defensions时,我想用粗体打印单词本身。 当我打印时

cout<<word<<endl<<defention1<<defenition2<<endl;

<代码> Cuth

标准C++使用各种区域/字符集显示各种字母表中的输出。但是,文本本身就是文本,没有格式

如果希望输出为
彩色
,或
粗体
,或
斜体
,则需要向终端发送适当的字符代码

但是,这是实现定义的,不保证在所有平台上都能工作

例如,在Linux/UNIX中,如果终端支持,则可以使用

适用于我的Mac OS X的示例:

#include <iostream>

int main()
{
    std::cout << "\e[1mBold\e[0m non-bold" << std::endl; // displays Bold in bold
}
#包括
int main()
{

std::cout标准
c++
无法以任何格式输出文本。但是,可以以粗体甚至不同颜色输出字符串。 这取决于您使用的操作系统和运行的终端/控制台

例如,在窗口的控制台中,无法用粗体书写文本。
如果您使用的是Linux/Unix,那么在大多数终端模拟器和虚拟控制台中,您可以用粗体编写字符串,甚至可以选择它的颜色,只需在字符串前添加
\e[1m
,在字符串后添加
\e[0m
,以确保其他字符串不会粗体

\e
是转义符号。在Vim中,只需按
ctrl+v+esc
即可编写转义符号

下面是Linux/Unix的一个简单示例(Mac也是Unix):

char esc_char=27;//转义字符的十进制代码是27

cout虽然我喜欢使用操纵器来加粗某些文本(正如@vsoftco所示),但我并不特别喜欢他使用的操纵器。就我个人而言,我更喜欢代码如下所示:

std::cout << bold(word) << definition1 << definition2;
class bold {
    std::string_view const &s;
public:
    bold(std::string_view const &s) : s(s) {}

    friend std::ostream &operator<<(std::ostream &os, bold const &b) {
        os << "\x1b[1m" << b.s << "\x1b[0m";
        return os;
    }
};
int main() {
    std::cout << bold("word") << " " << "definition\n";
}

std::cout正如@FalconUA提到的,如果您想“关闭”粗体显示,您需要额外输出一个
“\e[0m”
。@kass如果您使用最常用的终端,它应该可以工作。Windows 10中的控制台现在本机支持ANSI转义序列。您将对以下链接感兴趣:
class bold {
    std::string_view const &s;
public:
    bold(std::string_view const &s) : s(s) {}

    friend std::ostream &operator<<(std::ostream &os, bold const &b) {
        os << "\x1b[1m" << b.s << "\x1b[0m";
        return os;
    }
};
int main() {
    std::cout << bold("word") << " " << "definition\n";
}
std::cout << bold_on << a << b << c << d << bold_off;