Changing the colour of a single char in a 2D array

May 22, 2013 at 11:48pm
Hello,
I have a 2D array of chars that has a char (@) that I wish to change the colour of that individual char. I came up with some code that I think should have worked, but yielded no response. Here's part of the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <windows.h>

using namespace std;

char Map[10][20] = { "###################",
                     "#@................#",	
                     "#.................#",	
                     "#.................#",	
                     "#.................#", 
                     "#.................#",	
                     "#.................#",
                     "#.................#",	
                     "#.................#",
                     "###################" };

int main()
{
    for(int y = 0; y < 10; ++y)
    {
        if (Map[y] == "@")
        {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 10);
            cout << Map[y] << endl;
        }
        else
        {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 8);
            cout << Map[y] << endl;
        }
    }
    
    return 0;
}


This code ends up outputting the array as I want it to, but it doesn't change the colour of the "@" char. Any help?

Thanks in advance!
May 22, 2013 at 11:56pm
Shouldn't your output be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const int rows = 10 , columns = 20;
for( int i = 0; i < rows; ++i )
{
    for( int j = 0; j < columns; ++j )
    {
         if( Map[i][j] == '@' )
         {
             SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 10);
            cout << Map[y] << endl;
        }
        else
        {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 8);
            cout << Map[i][j] << endl;
        }
    }
}
May 23, 2013 at 12:21am
Wow, it works! I had a 1 dimensional pointer going through a 2 dimensional array because the console is rapidly refreshed, and it made it seem smoother. Now colours work, but it it a little bit choppy, since it's pointing through two for loops now, but that can be tolerated. Thanks for the help!
May 23, 2013 at 12:37am
Btw you should put the "Map" inside the main function globals aren't the best idea. Also in your case you could you could use a 1d array if you want but it'd be long with chars. Or you could make an array of strings maybe?
Topic archived. No new replies allowed.