mluong
mluong

Reputation: 1

How to store each user input into array?

I used a do while loop to ask user to enter integer as long as its not 0 or it will exit the program. I'm stuck on how to store every user input into the dynamically allocated array.

#include <iostream>
using namespace std;


int main() {
  int *A;
  A= new int();
  int n;
  do{
    cout<<"Enter integer: "<<endl;
    cin>>n;
    cout<< *A + n << endl;

    
  }while(n!=0);

  return 0;
}

Upvotes: 0

Views: 43

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595392

You are allocating a single int, not an array of ints.

Also, even if you were allocating an array, a statement like *A + n does not add n to the array. It dereferences A to access the value of the 1st int in the array, and then adds n to that value.

Try something more like this instead:

#include <iostream>
using namespace std;

int main() {
  int *A = nullptr;
  int count = 0, n;

  do{
    cout << "Enter integer: " << endl;
    cin >> n;
    if (n == 0) break;
    
    int *newA = new int[count+1];
    for(int i = 0; i < count; ++i) newA[i] = A[i];
    newA[count] = n;
    delete[] A;
    A = newA;
    ++count;

    cout << A[count-1] << endl;
  }
  while (true);

  delete[] A;

  return 0;
}

Alternatively, try to avoid reallocating the array on every input, eg:

#include <iostream>
using namespace std;

int main() {
  int *A = new int[5];
  int count = 0, cap = 5, n;

  do{
    cout << "Enter integer: " << endl;
    cin >> n;
    if (n == 0) break;
    
    if (count == cap)
    {
        int newCap = cap * 1.5;
        int *newA = new int[newCap];
        for(int i = 0; i < count; ++i) newA[i] = A[i];
        delete[] A;
        A = newA;
        cap = newCap;
    }

    A[count] = n;
    ++count;

    cout << A[count-1] << endl;
  }
  while (true);

  delete[] A;

  return 0;
}

That being said, a better option is to use a std::vector, which will handle the dynamic memory for you, eg:

#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> A;
  int n;
  do{
    cout << "Enter integer: " << endl;
    cin >> n;
    if (n == 0) break;
    A.push_back(n);
    cout << A.back() << endl;
  }
  while (true);

  return 0;
}

Upvotes: 2

Related Questions