我正在尝试更改控制台中文本的颜色。
我们应该使用配置文件从中读取ansi转义代码:
这是我的文件中的内容
red \033[0;31m #red
blue \033[0;34m #blue
green \033[0;32m #green
grey \033[0;37m #grey
这是我的代码:
#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;
}
不确定为什么,但只有最后一个print语句实际上以颜色显示,其他输出将ANSI转义码作为文本输出。
这是我的输出:
\033[0;34mblue
\033[0;32mgreen
\033[0;37mgrey
\033[0;31mred
hello (in purple)
\033
读入C++程序时会被解释为ESC。然而,事实并非如此。反斜杠只有对编译器运行的解析器有意义。对于文本输入,您作为程序员需要将\033
视为ESC。对于输入函数而言,它只是字符串{'\\', '0', '3', '3'}
。 - 5gon12eder\033[
)隐式地添加到程序中。这也会使配置文件看起来更简单。 - 5gon12eder