我试图改变控制台中文本的颜色.
我们应该使用配置文件来读取ansi转义码:
这就是我文件中的内容
red \033[0;31m #red
blue \033[0;34m #blue
green \033[0;32m #green
grey \033[0;37m #grey
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <fstream>
#include <map>
using namespace std;
int main(int argc, char * argv[]){
string file = "config.txt";
string line = "";
string tag = "";
string ansi = "";
map <string, string> m;
if(argc == 2){
file = argv[1];
}
ifstream in(file, ios_base::in | ios_base::binary);
if(!in){
cerr<<"could not open file";
}
while (getline(in, line)){
istringstream iss(line);
if(iss>>tag>>ansi){
auto it = m.find(tag);
if(it == m.end()){
m.insert(make_pair(tag,ansi));
}
}
}
for(auto x: m){
cout<<x.second<<x.first<<endl;
}
cout<<"\033[0;35mhello";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不确定为什么,但只有最后一个打印语句实际上以彩色显示,另一个输出ansi转义码作为文本.
这是我的输出:
\033[0;34mblue
\033[0;32mgreen
\033[0;37mgrey
\033[0;31mred
hello (in purple)
Run Code Online (Sandbox Code Playgroud)
而不是这样做:
cout<<"\033[0;35mhello";
Run Code Online (Sandbox Code Playgroud)
C++ 提供了编写自己的流操纵器(如 std::endl)来处理转义代码的可能性。
目标是编写这样的代码,对我来说似乎更具可读性:
cout << ansi::foreground_magenta << "hello" ;
Run Code Online (Sandbox Code Playgroud)
要编写自己的流操纵器,您可以像这样继续操作(简单的原始实现,但您需要从地图中获取值...):
#include <ostream>
namespace ansi {
template < class CharT, class Traits >
constexpr
std::basic_ostream< CharT, Traits > & reset( std::basic_ostream< CharT, Traits > &os )
{
return os << "\033[0m";
}
template < class CharT, class Traits >
constexpr
std::basic_ostream< CharT, Traits > & foreground_black( std::basic_ostream< CharT, Traits > &os )
{
return os << "\033[30m";
}
template < class CharT, class Traits >
constexpr
std::basic_ostream< CharT, Traits > & foreground_red( std::basic_ostream< CharT, Traits > &os )
{
return os << "\033[31m";
}
...
} // ansi
Run Code Online (Sandbox Code Playgroud)
或者,C 提供了使用#define 创建常量的可能性。
#define foreground_magenta "\033[35m"
Run Code Online (Sandbox Code Playgroud)
读取 config.txt 文件的问题是读取字符串时就好像它被分配为:
std::string str = "\\033[0;31m";
Run Code Online (Sandbox Code Playgroud)
即被\视为一个字符。您在代码中需要的是"\033",即八进制数表示的字符033。
您可以更改代码中的以下行以忽略"\\033"字符串部分并打印八进制数。
cout << x.second << x.first <<endl;
Run Code Online (Sandbox Code Playgroud)
需要是:
cout << '\033' << x.second.substr(4) << x.first <<endl;
Run Code Online (Sandbox Code Playgroud)
经过这一更改,我在桌面上尝试了您的程序,它按预期工作。
| 归档时间: |
|
| 查看次数: |
1597 次 |
| 最近记录: |