如何更改文本和背景颜色?

19

我希望每个字符都是不同的颜色。

例如:

cout << "Hello world" << endl;
  • H 将会变成红色
  • e 将会变成蓝色
  • l 将会变成橙色 以此类推。

我知道这是可以做到的,但我不知道代码怎么写。

而且我想把背景颜色改为白色。我该怎么做?

6个回答

16

没有(标准的)跨平台方法来实现这一点。在Windows上,尝试使用 conio.h。 它具有以下功能:

textcolor(); // and
textbackground();

函数。

比如:

textcolor(RED);
cprintf("H");
textcolor(BLUE);
cprintf("e");
// and so on.

9

SetConsoleTextAttribute函数。

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

这将在白色背景上产生红色文本。


7
您可以使用函数system
system("color *background**foreground*");

对于背景和前景,请输入0-9或A-F中的任意数字或字母。

例如:

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

这将显示带有绿色背景和蓝色文本的字母“hi”。

要查看所有颜色选择,只需输入:

system("color %");

查看数字或字母代表什么颜色。


3
它会改变整个控制台的颜色,并且在其他操作系统中不可移植。 - Desmond Gold

3
#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
您也可以使用PDCurses库。(http://pdcurses.sourceforge.net/)

2

颜色是按位编码的。如果您想在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;

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接