Search code examples
c++wstring

How do I write to a specific position in a wstring array?


I have a wstring named map and want to write to a specific position in that wstring array. I am able to read characters from specific positions, but I do not know how to write to this wstring other than to append to it.

float fPlayerX;
float fPlayerY;
int nMapWidth = 16;
int nMapHeight = 16;
bool GotO;

wstring map

map += L"################";
map += L"#G.............X";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#..............#";
map += L"#......O.......#";
map += L"#..............#";
map += L"#..............#";
map += L"################";

if (map.c_str()[(int)fPlayerX * nMapWidth + (int)fPlayerY] == 'O')
{
    // Pick up O
    if (GotO == false)
    { 
        // WRITE A "." TO WHERE THE O IS RIGHT NOW
    }
} 

If I try

map[(int)fPlayerX * nMapWidth + (int)fPlayerY] = L".";

or

map[(int)fPlayerX * nMapWidth + (int)fPlayerY] = ".";

I get

Error   C2440   '=': cannot convert from 'const wchar_t [2]' to 'wchar_t'

Solution

  • You can use map[index] = '.', where index is the position that you have computed.

    Be careful to use ' instead of "!. The expression '.' is of type char, whereas "." actually means the array {'.', '\0'} and is of type char const *.