-
Array Input
How would I fix this program so that the user is allowed to input any amount of numbers into the array? I'm absolutely confused.
Thanks in advance!
Code:
#include <iostream>
using namespace std;
int main()
{
double numbers[num_elements] = {};
int i;
for (i = 0; i < num_elements; i++)
{
cin >> numbers[i];
}
system ("pause");
return 0;
}
-
If you haven't learned about vector yet, now is the time. Arrays by definition have a maximum capacity so there you have it.
-
There are several options, and all are a little different than what you're trying to do in your example.
- Use a vector. The vector class is a standard library container that lets you add "any" amount of values to it. You could just keep pushing numbers on to the vector until the user stops or your machine runs out of memory.
- Make num_elements some big number and instead of allowing the user to input "any" amount of numbers, limit them to something less than that big number. For example, if you don't expect the user to ever enter more than 100 numbers, you could define num_elements as const in num_elements = 1000. Then just make sure they stop by the time they get to 1000.
- Use new[]/delete[] to make a dynamic array. This is similar to option one, but is not really recommended. I'd only do it if you're doing this for a class and you're not allowed to use vector or you're trying to learn how to manage memory with new[] and delete[].