【发布时间】:2012-04-01 15:39:36
【问题描述】:
我希望每个角色都有不同的颜色。
例如,
cout << "Hello world" << endl;
- H 会是红色的
- e 会是蓝色的
- l 将是橙色 等等。
我知道这可以做到,我只是不知道它的代码。
我想将背景颜色更改为白色。我该怎么做?
【问题讨论】:
我希望每个角色都有不同的颜色。
例如,
cout << "Hello world" << endl;
我知道这可以做到,我只是不知道它的代码。
我想将背景颜色更改为白色。我该怎么做?
【问题讨论】:
没有(标准)跨平台方法可以做到这一点。在 Windows 上,尝试使用 conio.h。
它有:
textcolor(); // and
textbackground();
函数。
例如:
textcolor(RED);
cprintf("H");
textcolor(BLUE);
cprintf("e");
// and so on.
【讨论】:
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
这将在白色背景上生成红色文本。
【讨论】:
您可以使用函数system。
system("color *background**foreground*");
对于背景和前景,请输入 0 - 9 之间的数字或 A - F 中的字母。
例如:
system("color A1");
std::cout<<"hi"<<std::endl;
这将显示带有绿色背景和蓝色文本的字母“hi”。
要查看所有颜色选择,只需输入:
system("color %");
看什么数字或字母代表什么颜色。
【讨论】:
您还可以使用 PDCurses 库。 (http://pdcurses.sourceforge.net/)
【讨论】:
`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)
}
【讨论】:
颜色是位编码的。如果你想改变 C++ 语言中的文本颜色有很多方法。在控制台中,可以更改输出的属性。click this icon of the console and go to properties and change color.
第二种方式是调用系统颜色。
#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;
}
【讨论】: