0
How to input an unspecified number of values?
Say I wanted a program to add some numbers, but I didn't want to specify how many numbers, how would I store the input? I tried using an array and leaving the initialisation as a user input, but it didn't work. Anybody else know how to do this? Thanks! I've put my attempt at the code below. I'm a complete beginner so please let me know if there's any obvious oversights/flaws :) https://code.sololearn.com/cpLSeW75BNON/?ref=app
5 Respuestas
+ 3
You can use dynamic memory allocation with new/delete. For example:
+ Read the number of numbers that user wants to sum, save it to num variable.
+ Allocate an array that has a size of num:
int[] arr = new int[num];
+ Read the numbers and store in arr.
+ Do the sum.
+ Release the memory with:
delete []arr;
Hope that helps.
+ 1
You cannot use an array that way. Arrays reserve memory according to their size and do not change.
You need a template class like list or vector. The differences between those are somewhat advanced, so just try either one.
+ 1
you should try to see if it works. I'm pretty sure it'll work
0
Thanks for the tip! I haven't gotten to the tutorial on templates yet, so I was wondering if there's a simpler way to do it
0
@Thoong Lee wouldn't that work the same without the "new" and "delete" operators?