Как изменить цвет текста и фона? - PullRequest
8 голосов
/ 01 апреля 2012

Я хочу, чтобы каждый символ был другого цвета.

например,

cout << "Hello world" << endl;
  • H будет красным
  • e будет синим
  • l будет оранжевым и т. д.

Я знаю, что это можно сделать, я просто не знаю код для этого.

и я хочу изменить цвет фона на белый. Как бы я это сделал?

Ответы [ 6 ]

10 голосов
/ 01 апреля 2012

Не существует (стандартного) кроссплатформенного способа сделать это. В Windows попробуйте использовать conio.h. Имеет:

textcolor(); // and
textbackground();

функция.

Например:

textcolor(RED);
cprintf("H");
textcolor(BLUE);
cprintf("e");
// and so on.
7 голосов
/ 16 мая 2014

Вы можете использовать функцию system.

system("color *background**foreground*");

Для фона и переднего плана введите число от 0 до 9 или букву от A до F.

Например:

system("color A1");
std::cout<<"hi"<<std::endl;

Это будет отображать буквы "привет" с зеленым фоном и синим текстом.

Чтобы увидеть все варианты цвета, просто наберите:

system("color %");

чтобы узнать, какой цифрой или буквой обозначен какой цвет.

5 голосов
/ 01 апреля 2012

SetConsoleTextAttribute .

HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);

Это приведет к появлению красного текста на белом фоне.

2 голосов
/ 30 декабря 2013
`enter code here`#include <stdafx.h> // Used with MS Visual Studio Express. Delete line if using something different
#include <conio.h> // Just for WaitKey() routine
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // For use of SetConsoleTextAttribute()

void WaitKey();

int main()
{

    int len = 0,x, y=240; // 240 = white background, black foreground 

    string text = "Hello World. I feel pretty today!";
    len = text.length();
    cout << endl << endl << endl << "\t\t"; // start 3 down, 2 tabs, right
    for ( x=0;x<len;x++)
    {
        SetConsoleTextAttribute(console, y); // set color for the next print
        cout << text[x];
        y++; // add 1 to y, for a new color
        if ( y >254) // There are 255 colors. 255 being white on white. Nothing to see. Bypass it
            y=240; // if y > 254, start colors back at white background, black chars
        Sleep(250); // Pause between letters 
    }

    SetConsoleTextAttribute(console, 15); // set color to black background, white chars
    WaitKey(); // Program over, wait for a keypress to close program
}


void WaitKey()
{
    cout  << endl << endl << endl << "\t\t\tPress any key";
    while (_kbhit()) _getch(); // Empty the input buffer
    _getch(); // Wait for a key
    while (_kbhit()) _getch(); // Empty the input buffer (some keys sends two messages)
}
2 голосов
/ 01 апреля 2012

Вы также можете использовать библиотеку PDCurses. (http://pdcurses.sourceforge.net/)

0 голосов
/ 13 мая 2017

Цвета имеют битовую кодировку. Если вы хотите изменить цвет текста на языке C ++, есть много способов. В консоли вы можете изменить свойства вывода. щелкните этот значок консоли и перейдите в свойства и измените цвет.

Второй способ - вызов системных цветов.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    //Changing Font Colors of the System

    system("Color 7C");
    cout << "\t\t\t ****CEB Electricity Bill Calculator****\t\t\t " << endl;
    cout << "\t\t\t  ***                MENU           ***\t\t\t  " <<endl;

    return 0;

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...