简体   繁体   中英

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;
}

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM