Q:

Trying to replace an element of a string array but only able to input a new string in that position. C++

Hello I am attempting to create a very simplified inventory system and I am having a slight issue. When trying to change an element in my string array, I am instead putting a new string value into the existing array and pushing everything else forwards.
// ConsoleApplication2.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <string>

int main()
{
    const int maxItems = 10; //Maximum number of items inventory can hold
    int numbItems = 0; //number of current items

    std::string inventory[maxItems]; //inventory

    //Items in inventory
    inventory[++numbItems] = "Sword";
    inventory[++numbItems] = "Cloak";
    inventory[++numbItems] = "Boots";

    //Show player items in inventory
    for (int i = 0; i <= numbItems; ++i)
    {
        std::cout << inventory[i] << "\n";
    }

    inventory[0] = "Axe"; //Replace sword with axe

    //Show player items in inventory
    for (int i = 0; i <= numbItems; ++i)
    {
        std::cout << inventory[i] << "\n";
    }

    //keep window open
    std::string barn;
    std::cin >> barn;

    return 0;
}

This code outputs; "axe, sword, cloak and boots" when the desired result is "axe, cloak and boots". 
Thank you in advance. 

A:

As far as I can see from your code, the numbItems for sword is 1 (you use pre-increment). Probably using post-increment will fix your problem.
Try using the code below (live IdeOne code):
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>

#include <string>

int main()
{
    const int maxItems = 10; //Maximum number of items inventory can hold
    int numbItems = 0; //number of current items

    std::string inventory[maxItems]; //inventory

    //Items in inventory
    inventory[numbItems++] = "Sword";
    inventory[numbItems++] = "Cloak";
    inventory[numbItems++] = "Boots";

    //Show player items in inventory
    for (int i = 0; i <= numbItems; ++i)
    {
        std::cout << inventory[i] << "\n";
    }

    inventory[0] = "Axe"; //Replace sword with axe

    //Show player items in inventory
    for (int i = 0; i <= numbItems; ++i)
    {
        std::cout << inventory[i] << "\n";
    }

    //keep window open
    std::string barn;
    std::cin >> barn;

    return 0;
}

On my computer, this works (the output is Sword,Cloak,Boots and Axe,Cloak,Boots).

A:

You use the preincrement-operator to fill your array.
inventory[++numbItems] = "Sword";

As numbItems starts at 0, you insert your first element at 1.
Just use the post-increment, and it will work fine.

