Write a function int* read_data(int& size) that reads data from cin until the user ter minates input by entering Q. The function should set the size reference parameter to the number of numeric inputs. Return a pointer to an array on the heap. That p r o G raMMin G e xer C ises cfe2_ch07_p307_350.indd 344 10/28/10 8:43 PM programming exercises 345 array should have exactly size elements. Of course, you won’t know at the outset how many elements the user will enter. Start with an array of 10 elements, and double the size whenever the array fills up. At the end, allocate an array of the correct size and copy all inputs into it. Be sure to delete any intermediate arrays.

Respuesta :

Answer:

look up the function in the explanation

Step-by-step explanation:

#include <iostream>

#include <cstdlib>

#include <string>

using namespace std;

int* read_data(int& size);

void print_array(int* array, int size); //used for testing

int main()

{

 int* array;

 int size;

 array = read_data(size);

 

 print_array(array,size);

 

}

int* read_data(int& size)

{

 string input="";

 

 size = 0;

 

 int capacity = 1; //used to store current capacity of array

 int* array = new int[1];

 cout << "Enter integer, Q to quit : " << endl;

 cin >> input;

 while(input != "Q")

 {

   array[size] = atoi(input.c_str());

   size++;

   //doubling capacity of array

   if (size==capacity)

   {

     //copy elements to temp array

     capacity *= 2;  

     int* temp = new int[size];

     for (size_t i = 0; i < size; i++)

     {

temp[i] = array[i];

     }

     //delete old array, allocate new array at new capacity

     delete[] array;

     array = new int[capacity];

     //copy temp array to new array  

     for (size_t i = 0; i < size; i++)

     {

array[i] = temp[i];

     }

     delete[] temp;

     

   }

 

   cin >> input;

 }

 

 

 int* temp = new int[size];

 for (size_t i = 0; i < size; i++)

 {

   temp[i] = array[i];

 }

 //if no values are entered return NULL

 if (size==0)

   return NULL;

 //delete old array, allocate new array at new capacity

 delete[] array;

 array = temp;  //make array point to temp array

 

 return array;  //return address of array

}

//print values of array for testing

void print_array(int* array, int size)

{

 for (size_t i = 0; i < size ; i++)

   cout << array[i] << " ";

 cout << endl;

}

ACCESS MORE