在C中将颜色应用于数组中的特定元素

时间:2014-11-23 08:57:25

标签: c colors

有没有办法只为数组中的一个元素着色?

说,我有一个像这样的2D数组:

main ()
{
int x,y;
char arr[3][3];
for (x=0;x<3;x++) 
for (y=0;y<3;y++) 
 arr[x][y]='a';

arr[1][1]='b';
for (x=0;x<3;x++) 
for (y=0;y<3;y++)
printf("%c", arr[x][y]);
}

如何将颜色仅应用于位于arr [1] [1]的字符'b'?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。适用于Windows的这个。如果你和我有同样的情况,我就是这样做的。 由于this question

中的答案很好,我使用了SetConsoleTextAttribute()函数

所以我的代码是

#include <windows.h>
#include <stdio.h>

main
{
enter code here
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
WORD saved_attributes;
char arr[3][3];
for (x=0;x<3;x++) 
for (y=0;y<3;y++) 
arr[x][y]='a';
arr[1][1]='b';
for (x=0;x<3;x++)
for (y=0;y<3;y++)
{
if (arr[x][y]=='b')
{
SetConsoleTextAttribute(hConsole, FOREGROUND_RED);
printf("%c", arr[x][y]);
SetConsoleTextAttribute(hConsole, saved_attributes);
}
else 
{
printf("%c", arr[x][y]);
}
}
相关问题