mardi 27 novembre 2018

Variables are being overwritten when I put values into an array

This function is supposed to take user inputs and put them into a map object. The width and length are being stored as variables in Map and id, x, and y are being stored in an array.

void Game::createMap()
{
    Map map1;
    int width;
    int length;
    int id;
    int x;
    int y;
    string answer = "1";


    cout << "Enter a map width: " << endl;
    cin >> width;
    cout << "Enter a map length: " << endl;
    cin >> length;
    map1.setWidth(width);
    map1.setLength(length);


    while(answer != "2")
    {
        cout << "Would you like to add a player? 1) Yes 2) No" << endl;
        cin >> answer;
        switch (stoi(answer))
        {
            case 1:
                cout << "Choose player id: " << endl;
                cin >> id;
                cout << "Enter an x coordinate: " << endl;
                cin >> x;
                cout << "Enter a y coordinate: " << endl;
                cin >> y;
                map1.setPlayers(id, x, y, map1.getNumPlayers());

                break;


            case 2:
                break;
            default:
                cout << "Enter a valid input" << endl;
                break;
        }
    }
    mapVector.push_back(map1);
}

This is the function that puts the user inputs into the array:

void Map::setPlayers(int x, int y, int player, int n)
{
    position[n][0] = player;
    position[n][1] = x;
    position[n][2] = y;
    cout << width << endl;
    cout << length;
}

For some reason, after the setPlayers function gets called, my width and length variables get set to the values gotten from the user for id and x. I do not know why these variables are being changed. It seems like when I am writing to the array it is overwriting the variables.

Aucun commentaire:

Enregistrer un commentaire