#include <stdio.h>
int main()
{
printf("\033[0;30Hello world!\n");
printf("\033[0;31Hello world!\n");
printf("\033[0;32Hello world!\n");
printf("\033[0;33Hello world!\n");
printf("\033[0;34Hello world!\n");
printf("\033[0;35Hello world!\n");
printf("\033[0;36Hello world!\n");
printf("\033[0;37Hello world!\n");
}
发帖说我感到很惭愧,但我完全不知道C,当我尝试用循环做这个时,它总是会产生一些错误。
我尝试过类似的东西:
for(int i=30; i<=37; i++){
char* color = "\033[0;"+itoa(i);
printf("%s Hello world", color);
}
好吧,大量的错误,比如我试图用int或somethink连接字符串。我也试过strcat,类型转换,给所有printf和设置%d而不是变量和其他一些东西。我正在研究虚拟机,它非常难,我需要它快速,依靠你的帮助。
顺便说一句:还有比30-37更多的颜色吗?我知道你可以用1而不是0等加粗。答案 0 :(得分:3)
要打印不同颜色的Hello字词,您可以使用:
#include <stdio.h>
#define KBCK "\x1B[30m" /* Black */
#define KRED "\x1B[31m" /* Red */
#define KGRN "\x1B[32m" /* Green */
#define KYEL "\x1B[33m" /* Yellow */
#define KBLU "\x1B[34m" /* Blue */
#define KMAG "\x1B[35m" /* Magenta */
#define KCYN "\x1B[36m" /* Cyan */
#define KWHI "\x1B[37m" /* White */
#define RESET "\033[0m"
int main(void){
printf(KBCK "Hello world! - in Black\n"RESET);
printf(KRED "Hello world! - in Red\n"RESET);
printf(KGRN "Hello world! - in Green\n"RESET);
printf(KYEL "Hello world! - in Yellow\n"RESET);
printf(KBLU "Hello world! - in Blue\n"RESET);
printf(KMAG "Hello world! - in Magenta\n"RESET);
printf(KCYN "Hello world! - in Cyan\n"RESET);
printf(KWHI "Hello world! - in White\n"RESET);
return 0;
}
你在那里有很多问题,你应该单独询问所有问题。
您可以查看ANSI color codes
正如Felix Palmer所说,你可以使用ncurses:
#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string){
size_t length=0;
int x, y;
float temp;
if(win == NULL)
win = stdscr;
getyx(win, y, x);
if(startx != 0)
x = startx;
if(starty != 0)
y = starty;
if(width == 0)
width = 80;
length = strlen(string);
temp = (float)(width - (int)length)/ 2;
x = startx + (int)temp;
mvwprintw(win, y, x, "%s", string);
refresh();
}
int main(void){
initscr(); /* Start curses mode */
if(has_colors() == FALSE)
{ endwin();
printf("Your terminal does not support color\n");
exit(1);
}
start_color(); /* Start color */
init_pair(1, COLOR_YELLOW, COLOR_BLACK);
attron(COLOR_PAIR(1));
print_in_middle(stdscr, LINES / 2, 0, 0, "This text should be Yellow");
attroff(COLOR_PAIR(1));
getch();
endwin();
return 0;
}
您可以通过更改以下内容来更改颜色:
init_pair(1, COLOR_YELLOW, COLOR_BLACK);
可用颜色为:
COLOR_BLACK 0 COLOR_RED 1 COLOR_GREEN 2 COLOR_YELLOW 3 COLOR_BLUE 4 COLOR_MAGENTA 5 COLOR_CYAN 6 COLOR_WHITE 7
答案 1 :(得分:2)
你想要这个:
for(int i=30; i<=37; i++){
char color[20];
snprintf(color, sizeof(color), "\033[%dm", i);
printf("%s Hello world\n", color);
}
甚至更简单,但前面的代码更具可读性
for(int i=30; i<=37; i++){
printf("\033[%dmHello world\n", i);
}
您的尝试有几个问题:
for(int i=30; i<=37; i++){
char* color = "\033[0;"+itoa(i); << - you can't add strings with '+'
- itoa requires 3 parameters
- you forgot the 'm' at the end of the
- escape sequence
printf("%s Hello world", color);
}
未经测试的代码,但它应该至少给你一个想法。