C ++ ansi escape codes not displaying color for console

I am trying to change the color of text in the console.

We must use the configuration file to read the ansi escape codes:

that's what is in my file

red     \033[0;31m      #red
blue    \033[0;34m      #blue
green   \033[0;32m      #green
grey    \033[0;37m      #grey

Here is my code:

    #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;
}

I don’t know why, but only the last print statement actually displays the color, the other displays the ansi escape codes as text.

Here is my conclusion:

\033[0;34mblue
\033[0;32mgreen
\033[0;37mgrey
\033[0;31mred
hello (in purple)
+4
source share
2 answers

The problem with reading config.txt files is that the line is being read as if assigned to it:

std::string str = "\\033[0;31m";

i.e. \regarded as a symbol. What you need in the code is "\033", that is, a character represented by an octal number 033.

, "\\033" .

    cout << x.second << x.first <<endl;

:

    cout << '\033' << x.second.substr(4) << x.first <<endl;

, .

+1

ESC.

, .

, ESC , .

:

red     31      #red
blue    34      #blue
green   32      #green
grey    37      #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<<"\033[0;"<<x.second<<"m"<<x.first<<endl;
    }
    cout<<"\033[0;35mhello";
    return 0;
}
+1

Source: https://habr.com/ru/post/1613069/


All Articles