Reputation: 45
I am writing a problem for school project on loops.
The program is a do-while loop where the user will feed the program sales figures, then expense figures for three separate districts. Then the user will be prompted to enter Y to enter the figures for another month, or anything else to terminate the loop.
After terminating the loop the program will then take the input figures for however many months the user has decided to evaluate and average them and compare them.
How do I store data for additional months and still keep the data for the first month?
Upvotes: 0
Views: 80
Reputation: 76
Seems like you would benefit from a dynamic data structure like a vector or list. If you're unfamiliar with std::vectors, they work like arrays but they grow and shrink as you add data to them. This will allow you to loop for as long as you like adding reports for an unknown amount of months.
Here you can see an example of how to use a vector.
So if I were you, I would build a struct or class that will represent the data for a month:
int main() {
struct report {
//sales figures
//district 1 expense report
//district 2 ...
//district 3 ...
int id = 0;
void printReport() { printf("ID: %d", id); }
};
//create vector that stores expense reports
std::vector<report> sales_reports;
char input = 'y';
while(input == 'y') {
//create report however you might choose to do that
report r;
r.id = 3;
sales_reports.push_back(r);
printf("Would you like to create another report? ");
input = getchar();
getchar();
printf("\n");
}
//Now you can iterate through your reports and print them out.
//You could write a print method for your report struct to easily print them.
for(int i = 0; i < sales_reports.size(); i++) {
sales_reports.at(i).printReport();
printf("\n");
}
The above code should compile so you can test it and get a feel for how it works. Keep in mind you can use vectors inside your report struct to make the info in there dynamic as well.
I'd take a close look at vector's and other dynamic data structure included in STL. They all accomplish what you're looking for but with different advantages.
Upvotes: 1
Reputation: 275220
Use a std vector. Have a struct containing data for a month. Once entered, you push back a copy into the vector.
Upvotes: 0