I have to write a program that reads a string of numbers from user input until it reads 0. For example if the values introduced are 1, 2, 3, 0 then the array X will contain 1, 2 and 3 and the array size will be 3. There is no specified limit for the number of values inserted and I can't just declare an array of any size so is there a way to dynamically increase the size of the array to be able to hold more int values as they are being read?
You can use a std::vector, which is a variable-length collection to which you can add elements. It manages reallocation automatically when needed. For example:
std::vector<int> values;
values.push_back(0);
values.push_back(1);
...
It's called Dynamic Memory Allocation check another question here
But normally i'd use a vector
#include <vector>
using namespace std;
int main(){
vector<int> v;
int x;
while(cin>>x && x != 0){
v.push_back(x);
}
}
You should note that vector class only exists by implementing dynamic memory allocation. It's just there for you and you don't need to do all the hard work like reserving and destroying the allocated memory...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With