C++ Printing Array

巧了我就是萌 提交于 2019-12-25 06:43:27

问题


So I have a 2d array I'm using as a gridmap where each array block is a space on a map.

So in my main() I've initialized array 'Map' with

char Map[ROWS][COLS]={'x'};

ROWS = 10 and COLS = 20

Later I call function PrintMap with

void PrintMap(const char Map[ROWS][COLS], const bool showTreasure)
{


for (int countr=0; countr<ROWS;countr++){
    for (int countc=0; countc<COLS;countc++){      //print map
            if (!showTreasure){
                    if (Map[countr][countc]!='T')
                            cout << Map[countr][countc];
                    else
                            cout << '*';
            } else {

                    cout << Map[countr][countc];

            }
    }
cout << endl;
}



}

One space on the grid is where the treasure or goal in the game is located. In the parameters for PrintMap is bool showTreasure which is whether or not you want a 'T' to be shown on the map or if you want to hide it.

So one of the spaces in the array will be a 'T' while all the others will be either '*', 'X', or 'P'.

The * is where nothing is located.

So the if statements are supposed to say: If showTreasure is false (meaning you want to hide the 'T'): you print what is in the array if it's not a 'T' or print an '*' if it is a T.

Now my problem is that even I've initialized the array with 200 *s, when I run the program it only prints out 1 *.


回答1:


If your initialization is this line:

char Map[ROWS][COLS]={'x'};

Then the matrix is initialized to a single x followed by 199 NULL characters.

See the excellent explanation at https://stackoverflow.com/a/201116/29157.

For more about std::fill() see https://stackoverflow.com/a/3948314/29157

Thanks for the tip, CantChooseUsernames!



来源:https://stackoverflow.com/questions/22925146/c-printing-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!