Hi there,

Is there a way to change strings array size on run time. I mean array size initial value is 1, when i run the program, how much user add values array size increases.

I have tried following but its not working, please i need a solution in array not in vector. Thanks !

#include <iostream>
#include <string>

using namespace std;

class ChangeSize
{
    private:

        string *arr;
        int size;
        int i;

    public:

        ChangeSize()
        {
            size = 1;
            arr = new string[size];
            i = 0;
        }

        void input()
        {
            char repeat;
            do
            {
                cout<<"Enter str item : "<<flush;
                cin >> arr[i];

                cout<<"Repeat (y/n)?"<<endl;
                cin >> repeat;

                if(repeat == 'y')
                {
                    i++;
                    size++;
                }

            }while(repeat == 'y');
        }

        void output()
        {
            cout<<"array : ";
            for(int i=0; i<size; i++)
                cout<<arr[i] <<" ";

            cout<<""<<endl;
        }
};

int main()
{
    ChangeSize ob;
    ob.input();
    ob.output();

    return 0;
}

Edited 3 Years Ago by pritaeas: Moved to C++

NOTE: this should be in the C++ forum thread.

You need after each input operation to increase the size of the array. Your constructor definition is good, initializing the data, but you must have another function, let's call it extendArray() which increases your array size. For example:

void extendArray(){
    string *newarr = new string[++size];
    for (int i=0;i<size-1;i++){
        newarr[i] = arr[i];
    }
    delete [] arr;
    arr = newarr;
}

Also, you should change your input function when the user enters the 'y' character to:

if(repeat == 'y')
{
    i++;
    extendArray();
}

Edited 3 Years Ago by Lucaci Andrew

This question has already been answered. Start a new discussion instead.