I am brand new to c++ and not sure how to store multiple user input without doing this
int a; int b; int c; int d; int e; int f; int g; int h; int i; int j; int k; int l; int m; int n; int o; int p; int q; int r; int s; int t; int u;
I'm trying to create a program that looks like this:
Please enter a number, -999 to exit:
10
20
30
40
50
60
70
-999
Your total is:
280
not necessarily lookin for a blatant answer as i'm tryin to learn for my uni course but if someone could point me in the right direction, it would be much appreciated
#include <iostream>
usingnamespace std;
int main() {
int total = 0;
int total1 = 0;
int entries[5];
entries[0,1,2,3,4]=0;
cout << "Please enter an integer. -999 to work out total." << endl;
while (entries[0,1,2,3,4] != -999){
cin >> entries[0];
cin >> entries[1];
cin >> entries[2];
cin >> entries[3];
cin >> entries[4];
}
if (entries[0,1,2,3,4] == -999) {
total= entries[0] + entries[1] + entries[2] + entries[3] + entries[4];
total1 = total + 999; //as the sentinel -999 is counted as an entry, adding it back cancels the final total out
cout << "The total is: " << total1<<endl;
}
system ("PAUSE");
return 0;
}
I'm having trouble with the array. The tutor doesn't want a limit on the amount of user input, so although more than 5 entries are allowed it's only allowing for 4 user inputs and the 5th must be the sentinel for the calculation to go ahead. Would i need to use a multidimensional array?
entries[0,1,2,3,4] == -999 This syntax does not compute. One would have to use a loop to look at each element in the array individually.
Are you allowed to use standard library containers? Probably not, because they would make this easy. They do allocate memory dynamically, but do hide how.
How about a compromise? Allocate statically a very big array. So big that any reasonable amount of input does fit in it.
Then, when reading values, do increase a counter. You do need anyway to tell which element to fill next. But you add two three conditions to stop the loop: input fails, input is -999, or counter reaches the size of the array.
On your summation you do not need to check for -999, because you never store it into the array. You do need a loop though.