-2

For a program I must use an array and not vector. I have to take in user's input, and it's a indefinite amount of them. The user can type in 5 values, or 50. I am absolutely stumped as to how to go about doing this. Using a for loop for example:

  Int a[10];
  Int b;
  For (int i=0; i<10; i++)
   {
     Cout<<"enter values:";
      Cin>>b;
       A[i]=b;
   }

With this I can take an array of 10 of user defined variables but how would I go about making it a dynamic size? Thank you for the help!

1 Answers1

0

The size of a static array must be known at compile time, otherwise you must use a dynamic array. For example

#include <iostream>

int main()
{
    // Determine how many total entries are expected
    int entries;
    std::cout << "How many values do you want to enter?" << std::endl;
    std::cin >> entries;

    // Allocate a dynamic array of the requested size
    int* a = new int[entries];

    // Populate the array
    for (int i = 0; i < entries; ++i)
    {
        std::cout << "enter a value: ";
        std::cin >> a[i];
        std::cout << std::endl;
    }

    // Clean up your allocated memory
    delete[] a;

    return 0;
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218