C++ 下划线输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24281603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ underline output
提问by user2326844
How can I underline a text which is supposed to be an output of a c++ code?
如何在应该是 C++ 代码输出的文本下划线?
Somewhere in the web I saw this:
我在网上的某个地方看到了这个:
cout<<underline<<"This is the text which is going to be underlined.";
But, for me this "underline" is not working. Any idea is very welcome.
但是,对我来说,这个“下划线”不起作用。任何想法都非常受欢迎。
回答by r3mainer
Are you outputting to an ANSI terminal? If so, the following escape sequence should work:
您是否正在输出到 ANSI 终端?如果是这样,以下转义序列应该有效:
#define underline "3[4m"
More information on ANSI escape sequences is available here.
Note: To turn underlining off again, use "\033[0m"
.
注意:要再次关闭下划线,请使用"\033[0m"
。
回答by Paul R
Probably the simplest and most portable method is just this:
可能最简单和最便携的方法就是这样:
cout << "This is the text which is going to be underlined." << endl;
cout << "-------------------------------------------------" << endl;
回答by Fedele
The following is an extensive example written for G++:
以下是为 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;
}
回答by Jérémy Pouyet
To complete Paul R answer, I sometimes create this function in my consol programs:
为了完成 Paul R 的回答,我有时会在我的控制台程序中创建这个函数:
std::string underline(const std::string &s) {
return std::string(s.length(), '-');
}
Then you can do:
然后你可以这样做:
int main() {
constexpr auto TEXT = "I am underlined";
std::cout << TEXT << std::endl << underline(TEXT) << std::endl;
return 0;
}
other possibilities:
其他可能性:
void underlineAndDisplay(const std::string &s);
std::string underlineWith(const std::string &s, char c);
Well, let's go back to my code...
好吧,让我们回到我的代码......