简体   繁体   English

C ++打印阵列

[英]C++ Printing Array

So I have a 2d array I'm using as a gridmap where each array block is a space on a map. 所以我有一个2d数组我用作网格图,其中每个数组块都是地图上的空格。

So in my main() I've initialized array 'Map' with 所以在我的main()中我用数据初始化了数组'Map'

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

ROWS = 10 and COLS = 20 ROWS = 10,COLS = 20

Later I call function PrintMap with 后来我用函数PrintMap调用

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. 在PrintMap的参数中是bool showTreasure,它是否要在地图上显示“T”或者是否要隐藏它。

So one of the spaces in the array will be a 'T' while all the others will be either '*', 'X', or 'P'. 因此,数组中的一个空格将是'T',而所有其他空格将是'*','X'或'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. 所以if语句应该说:如果showTreasure为false(意味着你想要隐藏'T'):你打印数组中的内容,如果它不是'T'或打印'*',如果它是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 *. 现在我的问题是,即使我用200 * s初始化数组,当我运行程序时它只打印出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. 然后将矩阵初始化为单个x后跟199个NULL字符。

See the excellent explanation at https://stackoverflow.com/a/201116/29157 . 请参阅https://stackoverflow.com/a/201116/29157上的优秀说明。

For more about std::fill() see https://stackoverflow.com/a/3948314/29157 有关std::fill()更多信息,请参阅https://stackoverflow.com/a/3948314/29157

Thanks for the tip, CantChooseUsernames ! 感谢您的提示, CantChooseUsernames

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM