1. Engineering
  2. Computer Science
  3. please finish the code in c open your exercise file...

Question: please finish the code in c open your exercise file...

Question details

Please finish the code in C++:

Open your exercise file and complete the TODOs in the C++ program which does the following: 1. It will read from a text file. Each line of the file contains a number. Provide the file name as a command line argument. Number of lines in the file is not known. 2. Create an array dynamically of a capacity (say 10) and store each number as you read from the file. 3. If you exhaust the array but yet to reach end of file dynamically resize/double the array and keep on adding.

#include <iostream>
#include <fstream>

using namespace std;


//Uncomment the lines and implement the TODOs in the resizing logic
void resize(int **arrayPtr, int *capacity)
{
   // TODO increase the capacity by two times
   int newCapacity =
cout<<"Resizing from "<<*capacity<<" to "<<newCapacity<<endl;

   // TODO dynamically allocate an array of size newCapacity
   int *newArray =

   // TODO copy all data from oldArray to newArray

   // TODO free the memory associated with oldArray

   *arrayPtr = newArray;
   *capacity = newCapacity;

}

int main(int argc, char* argv[])
{
   if(argc != 2)
   {
       return -1;
   }
   string filename = argv[1];
   ifstream data;
   data.open(filename.c_str());

   int capacity = 10;
   int *arrayPtr;

   // TODO Dynamically allocate space here for the array
   arrayPtr =
   int numOfElement = 0;
   string temp;

   if(data.is_open())
   {
       while(getline(data, temp))
       {
           int toBeInsert = stoi(temp);
           if(numOfElement == capacity)
           {
               // Complete this function
               resize(&arrayPtr, &capacity);
           }
           arrayPtr[numOfElement] = toBeInsert;
           numOfElement++;
       }
       data.close();
   }

   for(int i = 0; i < numOfElement; i++)
   {
       cout << "Num: " << arrayPtr[i] << endl;
   }
   return 0;
}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution