I'm trying to put together a program where the user enters the numbers in an array and then another function does some operations with the numbers entered.
It would look something like this:
"Enter numbers you want to be used: "
cin >> 0 43 2 45 3 6 34 1 3 ;
There's no minimum number restraints but the max would be 15 numbers used.
I have working code now but you have to input the number of numbers you will enter first, how can I write this code without the user first declaring how many numbers they will use first?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main (){
int *pointer = nullptr;
cout << "How many items are you going to enter?" << endl;
int input;
cin >> input;
pointer = newint[input];
int gameBoard;
for ( int counter = 0; counter < input; counter ++ ){
cin >> gameBoard;
* ( pointer + counter ) = gameBoard;
}
delete []pointer;
}
int *pointer = nullptr;
int input = 0;
int inputAmount = 0;
std::cout << "Insert A maximum of 15 elements in your array. (Insert -1 To Finish)" << endl;
while (input != -1)
{
cin >> input;
if (input != -1)
inputAmount++;
}
pointer = newint[inputAmount];
int gameBoard;
for (int counter = 0; counter < input; counter++){
cin >> gameBoard;
*(pointer + counter) = gameBoard;
}
delete[] pointer;
This increases "inputAmount" each time you input something. If you input -1, it will exit and insert that amount in the dynamic array.
only a few options I think:
- what you have, preset the input amount
- what TarikNeaj said, an escape character
- always get 15, but let user press enter (15-input) times to skip to end
- make user input numbers delimited by a space (i.e. all in a single line), so you can break the loop if encounter '\n'
Last one is best imo, maybe tricky if you don't understand buffers or getline.
First why do you need a dynamic array? You stated the maximum number of values is 15 so use that as the size of your array, then use the validated user entered number (must be 15 or less) as the condition of your data entry for() loop. Or use a "sentinel" along with this maximum size to control your entry loop.