I have been working on this for two weeks now and it has been progressing slowly. I am currently working on getting the the remove function of my program to 1. first check to see if there is a product 2. list the products 3. allow the user to select the product. 4. alow the user to delete a product. I think what I basically need to do is in Case2: create my list and check for my product there. Then I need to do a call to Remove function, which I will basically copy the add function with the exception of size -1 instead of size +1... at least those are my current thoughts. what would be the best way , must use the dynamic memory array and I am sort of stumped as to what to do next. Ideas to get me going with the remove again?

/************************************************************************

Name: Project 1

Purpose: Practice use of pointers in a actual program and 
         evaluation of the current skill set.

Description: dynamic array


************************************************************************/
#include <iostream>
#include <string>
using namespace std;

/***************************
     Prototypes
***************************/
void pause ();
int menu ();
string *addProduct (string *sptr, string newProduct, int size);
string *removeProduct (string *dptr, int i, int size);

double *addPrice (double *sptr, double newPrice, int size);
double *removePrice (double *dptr, int i, int size);


/***************************************
 This function is the point of entry for 
 the program.

 input parameters: None
 output Parameters: int - indication of the state of the program on close

****************************************/

int main()  
{
   int cont = 2;
   string *products;
   double *prices; 
   int size =0;


   do        
   {// start do
      int choice=menu ();
      switch (choice)
      { // Open switch statement
         case 1: 

              //Get the information from the user for the product
              char s[30];
              cout<<"\n\nEnter the product name: ";
              cin.getline(s,30);

              double price;
              cout<<"\n\nEnter the product Price: ";
              cin>>price;
              cin.ignore(80,'\n');

              products = addProduct(products,s, size);
              prices =   addPrice(prices,price, size);  
              size++;


              for (int i=0; i<size; i++)
                cout<<i<<": "<<*(products+i)<<"   "<<*(prices+i)<<endl;

            pause();
            break;

         case 2: 
            cout<<"\n\n Removed Called\n\n";
            break;

         case 3: 
            cout<<"\n\n Sort Called\n\n";
            break;

         case 4: cont=0;
            break;
      } // Close switch statement

   }while (cont ==2);
   return 0;
}// STOP MAIN



void pause ()
{
   cout << "Press enter to continue " << endl;
   cin.ignore (80, '\n');
}



int menu () 
{ // start int menu prototype

   int c = -1;
   while (c<1 || c>4)
   {  // start menu
      system ("cls");
      cout << " 1. Add\n\n\n"
           << " 2. Omit\n\n\n"
           << " 3. Sort\n\n\n"
           << " 4. Exit\n\n\n"
           << " Please make a selection from the menu: \n\n";

      cin >> c;
      cin.ignore (80, '\n');
   }//end of while loop
   return c;
}// close int menu prototype



string *addProduct (string *sptr, string newProduct, int size)
{
   //Create a new memory location and store the memory location in the pointer.
   string *ptr = new string[size+1];

   //Move the products to the new memory location
   for (int i=0; i<size; i++)
      *(ptr+i)=*(sptr+i);
   //add the new product to the new memory location      
   *(ptr+size)=newProduct;

   //if the size is not 0 then delete the old memory location
    if (size>0)
       delete sptr; 
    //Return the new memory location pointer
    return ptr; 
}//stop void add prototype


string *removeProduct (string *dptr, int i, int size)
{
   cout << " Remove ";
   pause();
}//stop void omit prototype


double *addPrice (double *dptr, double newPrice, int size)
{
//Create a new memory location and store the memory location in the pointer.
   double *ptr = new double[size+1];

   //Move the prices to the new memory location
   for (int i=0; i<size; i++)
      *(ptr+i)=*(dptr+i);
   //add the new price to the new memory location      
   *(ptr+size)=newPrice;

   //if the size is not 0 then delete the old memory location
    if (size>0)
       delete dptr; 
    //Return the new memory location pointer
    return ptr;        

}

double *removePrice (double *dptr, int i, int size)
{}

Recommended Answers

All 7 Replies

Can you use classes? Have you learned them yet? It'd be a ton easier to manage your array through one.

Also there's quite a bit of errors in your code.. You're using the wrong delete :l

If you do: new[Size] then you need to do delete[].. If you use new then you use delete. Notice the square brackets.

You can always create something like this if you MUST do things manually and are allowed to:

#include <iostream>

using namespace std;


template<typename T>
class DynamicArray
{
    private:
        T* _Data;
        int _Size, _Cap;

    public:
        DynamicArray(int Capacity) : _Data(new T[Capacity]), _Size(0), _Cap(Capacity) {}
        ~DynamicArray() {delete[] _Data; _Data = nullptr; _Size = 0; _Cap = 0;}

        int size() {return _Size;}
        int capacity() {return _Cap;}
        T Get(int Index) {return _Data[Index];}

        void Resize(int NewCapacity);
        void Add(const T &Data);
        void Remove(int Index);
};

template<typename T>
void DynamicArray<T>::Resize(int NewCapacity)
{
    T* Temp = new T[NewCapacity];
    int Max = std::max(_Size, _Cap = NewCapacity);
    std::copy(_Data, _Data + _Size, Temp);
    delete[] _Data;
    _Data = Temp;
}

template<typename T>
void DynamicArray<T>::Add(const T &Data)
{
    if (_Size < _Cap)
    {
        _Data[_Size++] = Data;
    }
    //throw std::runtime_error("Error. Max Capacity Reached. Resize the array.");
}

template<typename T>
void DynamicArray<T>::Remove(int Index)
{
    if (Index < _Size && _Size != 0)
    {
        for (int I = Index; I < _Size - 1; ++I)
        {
            _Data[I] = _Data[I + 1];
        }
        _Data[--_Size] = T();
    }
}

int main()
{
    DynamicArray<std::string> Dim(5);

    Dim.Add("Hello");
    Dim.Add("One");
    Dim.Add("Two");
    Dim.Add("Three");
    Dim.Add("Four");

    Dim.Resize(10);

    Dim.Add("Five");
    Dim.Add("Six");
    Dim.Remove(0);

    for (int I = 0; I < Dim.size(); ++I)
    {
        std::cout<<Dim.Get(I)<<"\n";
    }
}

Just an example.. It'd be wise to just use vectors if you could.. But the above just demonstrates how to manage your dynamic array without having to worry about deleting/cleaning up.. It shows you how to add and remove from the array. Perhaps, if you're not allowed to create classes or don't understand them, you can just use the same logic and put it into a function and call that to do the addition/removal for you.

It works like this:

  1. Find the index you want to remove.
  2. Using a for loop, start at that index and shift/copy the next element to the left(current index).
  3. Finally, just null/default out the last element.

You can also use std::copy instead of the forloop/shift left. You'll still have to default/null out the last value. Another option is std::move. These are all just options. It's up to you to choose what fits best or what you understand easiest.

Also, can you use standard template library collection classes, such as std::vector<T>? Or do you need to support your own collection classes/functions/methods?

i need an array program can u help me ?

what do you need it for ?

thanks for the replies guys. I have to stick with what I have here is what I have so far now , I need a sort and it should be good I think thanks for the Ideas.

/************************************************************************

Name: Project 1

Purpose: Practice use of pointers in a actual program and 
         evaluation of the current skill set.

Description: Put the project description here


************************************************************************/
#include <iostream>
#include <string>
using namespace std;

/***************************
     Prototypes
***************************/
void pause ();
int menu ();
string *addProduct (string *sptr, string newProduct, int size);//string ptr return type
string *removeProduct (string *dptr, int index, int size);//string ptr return type
//void arrSelectSort(int *[], int);
//void showArray(const int [], int);
//void showArrPtr(int *[], int);

double *addPrice (double *sptr, double newPrice, int size);//double ptr, return type,
double *removePrice (double *dptr, int index, int size);//double ptr, return type,


/***************************************
 This function is the point of entry for 
 the program.

 input parameters: None
 output Parameters: int - indication of the state of the program on close

****************************************/

int main()  
{
   int cont = 2;
   string *products;//ptr to dynamic array to hold names of products
   double *prices; //ptr to dynamic array to hold prices of products
   int size =0;//hold the size of the dynamic array


   do        
   {// start do
      int choice=menu (); // call to the menu function
      switch (choice)
      { // Open switch statement
         case 1: 

              //Get the information from the user for the product
              char s[30];
              cout<<"\n\n Enter the product name:  ";
              cin.getline(s,30);

              double price;
              cout<<"\n\n Enter the product Price:  ";
              cin>>price;
              cin.ignore(80,'\n');

              products = addProduct(products,s, size);
              prices =   addPrice(prices,price, size);  
              size++;


              for (int i=0; i<size; i++)
                cout<< i+1 << ": " <<*(products+i)<< "     " <<*(prices+i)<<endl;

            pause();
            break;

         case 2:
              int ridx;
            if(size<0)
               cout<<"The list is currently empty\n\n";
            else
             {
              for (int i=0; i<size; i++) 
              cout<< i+1 << " : " <<*(products+i)<< "     " <<*(prices+i)<<endl;
              }

              cout<<"\n\nplease select a product you would like to remove: ";
              cin>>ridx;
              cin.ignore(80,'\n');
              cout<<ridx<<endl;
              pause();
              products = removeProduct(products,ridx, size);
              prices = removePrice(prices,ridx, size);  
              size--;

             break;

         case 3: 
            cout<<"\n\n we are now going to sort the products\n\n";
            break;

         case 4: cont=0;
            break;
      } // Close switch statement

   }while (cont ==2);
   return 0;
}// STOP MAIN



void pause ()
{
   cout << "Press enter to continue " << endl;
   cin.ignore (80, '\n');
}



int menu () 
{ // start int menu prototype

   int c = -1;
   while (c<1 || c>4)
   {  // start menu
      system ("cls");
      cout << " 1. Add\n\n\n"
           << " 2. Remove\n\n\n"
           << " 3. Sort\n\n\n"
           << " 4. Exit\n\n\n"
           << " Selection: \n\n";

      cin >> c;
      cin.ignore (80, '\n');
   }//end of while loop
   return c;
}// close int menu prototype



string *addProduct (string *sptr, string newProduct, int size)
{
   //Create a new memory location and store the memory location in the pointer.
   string *ptr = new string[size+1];

   //Move the products to the new memory location
   for (int i=0; i<size; i++)
      *(ptr+i)=*(sptr+i);
   //add the new product to the new memory location      
   *(ptr+size)=newProduct;

   //if the size is not 0 then delete the old memory location
    if (size>0)
       delete sptr; 
    //Return the new memory location pointer
    return ptr; 
}//stop void add prototype

/****************************************************************/
/*remove product function/
/****************************************************************/
string *removeProduct (string *dptr, int index, int size)
{
//Create a new memory location and store the memory location in the pointer.       
string *ptr2=new string[size-1];
int idex=0;
//Move the products to the new memory location
for(int i=0;i<size;i++)
{
if(index!=i+1)
{
*(ptr2+idex)=*(dptr+i);
idex++;
}
}
//if the size is not 0 then delete the old memory location
   If (size>0)
       delete [] dptr;
       dptr=0;
  //Return the new memory location pointer     
   return ptr2;
}//stop void remove prototype


double *addPrice (double *dptr, double newPrice, int size)
{
//Create a new memory location and store the memory location in the pointer.
   double *ptr = new double[size+1];

   //Move the prices to the new memory location
   for (int i=0; i<size; i++)
      *(ptr+i)=*(dptr+i);
   //add the new price to the new memory location      
   *(ptr+size)=newPrice;

   //if the size is not 0 then delete the old memory location
    if (size>0)
       delete dptr; 
    //Return the new memory location pointer
    return ptr;        

}

double *removePrice (double *dptr, int index, int size)
{
 //Create a new memory location and store the memory location in the pointer.      
 double *ptr3=new double[size-1];
int idex=0;
//Move the prices to the new memory location
for(int i=0;i<size;i++)
{
if(index!=i+1)
{
*(ptr3+idex)=*(dptr+i);
idex++;
}
}
//if the size is not 0 then delete the old memory location
    if (size>0)
       delete dptr; 
    //Return the new memory location pointer
    return ptr;        

 return ptr3;

       }

what do you think about doing the arrselectsort and showarray for this would it be good or would just a standary sort be better?

Member Avatar for iamthwee

@triumphost surely you can tell from the OP's post that this is probably homework and that he is probably not ready for templates. Just saying...

It surprises me how some long standing members still like to throw highly abstract examples at newbies doing homework questions.

@iamthwee
I can tell that its homework but I wasn't sure since he said "2 week project" or something; I wasn't sure if its a personal one or not.. I did assume it was homework however. What I can't tell from his post is what he is allowed to use and what he's not allowed to do.

I was just asking and not throwing templates at him. I was just giving him an idea.. Its not the template that he should really be looking at but the logic within it.. The template was just there to make his life easier IF he was allowed to use it. I can't just assume that he's not allowed since he never really stated his limitations or what he wants done. All he said was "what would be the best way, must use the dynamic memory array and I am sort of stumped as to what to do next."

And what I mentioned allows him to use "dynamic memory".. Yeah you are right though. He probably isn't ready for it but again, its just a bunch of examples crammed into a class.. I was hoping he'd figure out how it works and sorta use that as an example of where to get started..

.
.
.
.

@OP.. You are still using the wrong delete... If you use new[Size] you need to use delete[].. not delete.

Example:

string* p = new string[Size];

//the above MUST be deleted using delete[]; not delete. Notice the square brackets again.
//Thus the below is what you need to do:

delete[] p;


//However, if you do:

string* s = new string;

//then you need to delete it using delete. NOT delete[].
//Thus the below is correct:

delete s;

//All in all:
SomePtr = new DataType            ->   delete SomePtr;
SomePtrArr = new DataType[Size]   ->   delete[] SomePtrArr;

Next. A bunch of case statements are wrong.. for example, if the list is empty then why give the user the option to remove from the list? This is happening in Case 2. If the list is empty, you need to break from the switch after letting them know that its empty. The condition should be "if (size <= 0)". Without breaking immediately and having the right condition, your case throws std::bad_alloc.

Next. I'm not sure why you're using a char[30] and constructing a string from that? You can just do cin>>s; where s is a std::string. Also using cin.ignore() after the input will make it ignore the enter button and print the next statement.

Next. You cannot return from the same function twice.. Look at your removePrice function. It has two return statements within the same scope. The last return statement will never execute..

Next. To pause the program, just use cin.get().. what you're using right now makes the user have to press enter more than once to see the next statement printed out..

Finally, you never validate the input.. if I enter "Meh" for the price, your program enters an infinite loop and never stops.. thus you need to check like:

if (!std::cin.good())
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout<<"Invalid Input...\nPress Enter To Continue..";
    std::cin.get();
}

I don't do homework but I did take the time to fix your errors. I did not "write any of logic" or any code for you. I only fixed what was already there and added the validation I showed above.

Thus all in all, something like this is what you want to start off with then you can move onto your sorting algorithm:

/************************************************************************

Name: Project 1

Purpose: Practice use of pointers in a actual program and
         evaluation of the current skill set.

Description: Put the project description here


************************************************************************/
#include <iostream>
#include <string>
#include <limits>
using namespace std;

/***************************
     Prototypes
***************************/
void pause ();
int menu ();
string* addProduct (string* sptr, string newProduct, int size);
string* removeProduct (string* dptr, int index, int size);
double* addPrice (double* sptr, double newPrice, int size);
double* removePrice (double* dptr, int index, int size);

int main()
{
    int cont = 2;
    string* products;
    double* prices;
    int size = 0;

    do
    {
        int choice = menu();
        switch (choice)
        {
            case 1:    //Adds a new product to the list and prints the entire list.
            {
                string s;
                cout << "\n\n Enter the product name:  ";
                cin>>s;
                cin.ignore();

                double price;
                cout << "\n\n Enter the product Price:  ";
                cin >> price;
                cin.ignore();

                products = addProduct(products, s, size);
                prices = addPrice(prices, price, size);
                ++size;

                for (int i = 0; i < size; i++)
                    cout << i + 1 << ": " << *(products + i) << "     " << *(prices + i) << endl;

                pause();
            }
            break;

            case 2:
                int ridx;
                if(size <= 0)
                {
                    cout << "The list is currently empty\n\n";
                    pause();
                    break;
                }
                else
                {
                    for (int i = 0; i < size; i++)
                        cout << i + 1 << " : " << *(products + i) << "     " << *(prices + i) << endl;
                }

                cout << "\n\nplease select a product you would like to remove: ";
                cin >> ridx;
                cin.ignore();
                cout << ridx << endl;
                pause();
                products = removeProduct(products, ridx, size);
                prices = removePrice(prices, ridx, size);
                size--;

                break;

            case 3:
                cout << "\n\n we are now going to sort the products\n\n";
                break;

            case 4:
                cont = 0;
                break;
        }

    }
    while (cont == 2);
    return 0;
}



void pause ()
{
    cout << "Press enter to continue " << endl;
    cin.get();
}



int menu ()
{
    int c = -1;
    while (c < 1 || c > 4)
    {
        system ("cls");
        cout << " 1. Add\n\n\n"
             << " 2. Remove\n\n\n"
             << " 3. Sort\n\n\n"
             << " 4. Exit\n\n\n"
             << " Selection: \n\n";

        cin >> c;
        cin.ignore();

        if (!cin.good())
        {
            c = -1;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout<<"Invalid Input. Please try again.\n";
            pause();
        }
    }
    return c;
}



string* addProduct(string* sptr, string newProduct, int size)
{
    string* ptr = new string[size + 1];

    for (int i = 0; i < size; i++)
        *(ptr + i) = *(sptr + i);

    *(ptr + size) = newProduct;

    if (size > 0)
        delete[] sptr;
    return ptr;
}


string* removeProduct (string* dptr, int index, int size)
{
    string* ptr2 = new string[size - 1];
    int idex = 0;
    for(int i = 0; i < size; i++)
    {
        if(index != i + 1)
        {
            *(ptr2 + idex) = *(dptr + i);
            idex++;
        }
    }

    if (size > 0)
        delete [] dptr;
    dptr = 0;

    return ptr2;
}


double* addPrice(double* dptr, double newPrice, int size)
{
    double *ptr = new double[size + 1];
    for (int i = 0; i < size; i++)
        *(ptr + i) = *(dptr + i);

    *(ptr + size) = newPrice;

    if (size > 0)
        delete[] dptr;
    return ptr;
}

double* removePrice (double* dptr, int index, int size)
{
    double *ptr3 = new double[size - 1];
    int idex = 0;

    for(int i = 0; i < size; i++)
    {
        if(index != i + 1)
        {
            *(ptr3 + idex) = *(dptr + i);
            idex++;
        }
    }

    if (size > 0)
        delete[] dptr;

    return ptr3;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.