如何在 C++ 中创建动态字符数组

问题描述

我正在尝试在 C++ 中创建一个动态字符数组,但是当我创建它时,它只会产生一些错误,因为我正在尝试向其中添加字符,我将在此处输入代码。我知道我可以把它做成一个字符串,但它需要更多的空间,而且使用动态阵列会更酷:太阳镜:

#include <iostream>
#include <string>
using namespace std;
int main()
{
int mapx; int mapy; int xpl = 8; int ypl = 8; char action = ' '; int score = 0;  // var declaraction 
cout << "enter the x and then y of the map \n";
cin >> mapx;
cin >> mapy;
xpl = mapx / 2;
ypl = mapy / 2;
int coinx = rand() % mapx;
int coiny = rand() % mapy;
char* map = new char(mapx * mapy);
while (action != 'e') { // runs the game

    for (int y = 0; y <= mapy; y++) { // generates the y of the map

        for (int x = 0; x <= mapx; x++) { // generates the x of the map + the player 
            if (x == xpl && y == ypl) {
                map += "X";
            }
            else if (x == coinx && y == coiny) map += "C";
            else {
                map += "_";
            }
        } // end of x+player for
        map += "\n"; 
        if (xpl == coinx && ypl == coiny) { //checks if player hit coin
                coinx = rand() % mapx;
                coiny = rand() % mapy;
                score++;
        }
    } // end of y for
    cout << map + "Enter an action ";
    cin >> action; // movement
    if (action == 'w') ypl--;
    else if (action == 's') ypL++;
    else if (action == 'd') xpL++;
    else { xpl--; }
    // checks what the move is
    map = ""; //resets the map
    
} // end of game
cout << "GAME OVER " << score;
}   // end of main

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)