반응형

출처:

https://stackoverflow.com/questions/8626939/is-there-is-any-alternatives-to-cprintf/8628104#8628104?s=cebcf31bd06c4abbb8147aba5f55be31

http://web.cs.mun.ca/~michael/c/ascii-table.html

http://forum.falinux.com/zbxe/index.php?document_srl=568150&mid=lecture_tip

http://cc.byexamples.com/2007/01/20/print-color-string-without-ncurses/



#include <stdio.h>

// 상수 변수 선언
enum {RESET, BRIGHT, DIM, UNDERLINE, BLINK};
enum {REVERSE = 7, HIDDEN};
enum {BLACK, RED, GREEN, YELLOW, BLUE, MAGNETA, CYAN, WHITE};

void textcolor(int attr, int fg, int bg) {
    char command[13];
    sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
    printf("%s", command);
}

int main() {
    textcolor(BRIGHT, BLUE, WHITE);
    printf("ABC");
    getchar();
    system("reset"); // 본래 설정으로 되돌아가기 위함
    return 0;
}



솔직히 어떻게 저렇게 되는 건지는 잘 모르겠다.

그냥 저렇게 되는 거라고만 알자.

0x1B는 esc 문자이고, attr는 서식 지정을 위한 매개변수,

fg는 글자색, bg는 배경색 변화를 위한 매개변수이다.


그리고 system("reset") 명령어는 변경된 설정을 다시 원래대로 하기 위함이다.

getchar()를 먼저 호출한 다음 위 함수를 호출해야 하는데

그렇지 않으면 위의 코드에서 바뀐 색상 상태로 계속해서 실행되기 떄문이다.

그래서 저 코드를 그대로 실행하고 나면 getchar() 호출로 인해 아무키나 하나 누르면,

system("reset") 으로 화면을 다 지우고 원래 상태로 되돌아오게 함을 볼 수 있다.


참고로 윈도우는 다음과 같이 한다.

http://blockofcodes.blogspot.kr/2013/06/how-to-change-text-color-of-cc-console.html


근데 나는 저기에서 stdlib.h 헤더를 넣지 않아도 되더라.

반응형
Posted by 애콜라이트
l

free counters