How to allow user to enter input into an array without a limit?

closed account (LN7oGNh0)
I know you can dynamically allocate memory, but i'm not really getting how to do it. Also, i'm pretty sure vectors would be good for this. I've read about these two things, but I don't get them that much... Basically I don't want the user only able to enter 4 numbers, but as many as they want until a certain condition has been met. (like in a loop). Any ideas?

Thanks.
Yeah, a vector is the best choice for you.

1
2
3
4
5
6
7
8
9
10
11
12
13
std::vector<int> Numbers; // Here, your numbers will be stored.

bool CanInputNumbers = 1;
while(CanInputNumbers)
{
    int NewNumber = 0;
    cin >> NewNumber; // Get the number to add to the vector
    Numbers.push_back(NewNumber); // Add it to the vector
}

unsigned int NumberOfNumbers = Numbers.size(); // How many numbers are there?
int First = Numbers[0]; // First number user did input? Error here if user did not input any
int Last = Numbers[NumberOfNumbers-1]; // Last number user did input? Error here if user did not input any 


http://www.cplusplus.com/reference/vector/vector/
Last edited on
Without dynamic allocation:
1
2
3
4
5
6
7
int arr[4];

for (int i = 0; i < 4; ++i)
{
  cin >> arr[i];
  if (arr[i] < 0) break;
}


With dynamic allocation (no hard-coded limit of 4)
1
2
3
4
5
6
7
8
9
10
11
int size = 0;
int* arr;
do
{
  int* newArray = new int[++size];
  for (int j = 0; j < size-1; ++j)
    newArray[j] = arr[j];
  delete[] arr;
  arr = newArray;
  cin >> arr[size-1];
} while ( arr[size-1] >= 0);


With vectors (no hard-coded limit of 4)
1
2
3
4
5
6
7
8
std::vector<int> vect;
while(true)
{
  int temp;
  cin >> temp;
  if (temp < 0) break;
  vect.push_back(temp);  
}
Last edited on
closed account (LN7oGNh0)
Thank you for quick replies and good examples!
Topic archived. No new replies allowed.