【问题标题】:C++ underline outputC++ 下划线输出
【发布时间】:2014-08-08 12:23:03
【问题描述】:

如何在应该是 c++ 代码输出的文本下划线?

我在网上的某个地方看到了这个:

cout<<underline<<"This is the text which is going to be underlined.";

但是,对我来说,这个“下划线”不起作用。任何想法都非常受欢迎。

【问题讨论】:

  • 我不相信标准 C++ 可以做到这一点,可能使用 QT 之类的 UI 框架
  • 标准 C++ 无法做到这一点,Google 'ncurses'。
  • 如果你继续 yahoo 回答,最好的答案是这样开始的:“我希望你不要期待一些简单的东西,比如:cout &lt;&lt; underline &lt;&lt; "this text should be underlined";
  • 不是标准!

标签: c++ underline


【解决方案1】:

可能最简单和最便携的方法就是这样:

cout << "This is the text which is going to be underlined." << endl;
cout << "-------------------------------------------------" << endl;

【讨论】:

  • 有时最简单的答案就是最好的答案。 ;-)
【解决方案2】:

您要输出到 ANSI 终端吗?如果是这样,下面的转义序列应该可以工作:

#define underline "\033[4m"

More information on ANSI escape sequences is available here.

注意:要再次关闭下划线,请使用"\033[0m"

【讨论】:

    【解决方案3】:

    为了完成 Paul R 的回答,我有时会在我的控制台程序中创建这个函数:

    std::string underline(const std::string &s) {
        return std::string(s.length(), '-');
    }
    

    那么你可以这样做:

    int main() {
        constexpr auto TEXT = "I am underlined";
        std::cout << TEXT << std::endl << underline(TEXT) << std::endl;
        return 0;
    }
    

    其他可能性:

    void underlineAndDisplay(const std::string &s);
    std::string underlineWith(const std::string &s, char c);
    

    好吧,让我们回到我的代码...

    【讨论】:

      【解决方案4】:

      以下是为 G++ 编写的扩展示例:

      #include <iostream>
      using namespace std;
      int  main()
      {
          char normal[]={0x1b,'[','0',';','3','9','m',0};
          char black[]={0x1b,'[','0',';','3','0','m',0};
          char red[]={0x1b,'[','0',';','3','1','m',0};
          char green[]={0x1b,'[','0',';','3', '2','m',0};
          char yellow[]={0x1b,'[','0',';','3', '3', 'm',0};
          char blue[]={0x1b,'[','0',';','3','4','m',0};
          char Upurple[]={0x1b,'[','4',';','3','5','m',0};
          char cyan[]={0x1b,'[','0',';','3','6','m',0};
          char lgray[]={0x1b,'[','0',';','3','7','m',0};
          char dgray[]={0x1b,'[','0',';','3','8','m',0};
          char Bred[]={0x1b,'[','1',';','3','1','m',0};
          //for bold colors, just change the 0 after the [ to a 1
          //for underlined colors, just change the 0 after the [ to a 4
          cout<<"This text is "<<black<<"Black "<<red<<"Red ";
          cout<<green<<"Green "<<yellow<<"Yellow "<<blue<<"Blue\n";
          cout<<Upurple<<"Underlined Purple "<<cyan<<"Cyan ";
          cout<<lgray<<"Light Gray "<<dgray<<"Dark Gray ";
          cout<<Bred<<"and Bold Red."<<normal<<"\n";
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-10
        • 2021-01-13
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        相关资源
        最近更新 更多