如何存储未知次数迭代的输入?

How to store input for an unknown number of iterations?

本文关键字:迭代 输入 未知 何存储 存储      更新时间:2023-10-16

我正在为循环的学校项目编写一个问题。

该程序是一个do-while循环,用户将输入程序销售数据,然后是三个不同地区的费用数据。然后,系统将提示用户输入 Y 以输入另一个月的数字,或者任何其他内容来终止循环。

终止循环后,程序将获取用户决定评估和平均它们并进行比较的输入数字。

如何将数据存储再存储几个月,同时仍保留第一个月的数据?

似乎您会从动态数据结构(如向量或列表(中受益。如果您不熟悉 std::vectors,它们的工作方式类似于数组,但随着您向它们添加数据,它们会增长和收缩。这将允许您循环,只要您喜欢添加未知数量的报告。

在这里,您可以看到如何使用向量的示例。

因此,如果我是你,我会构建一个结构或类来表示一个月的数据:

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");
}

上面的代码应该编译,以便您可以对其进行测试并了解它的工作原理。请记住,您可以在报表结构中使用向量来使其中的信息也动态化。

我会仔细研究STL中包含的向量和其他动态数据结构。它们都完成了您正在寻找的目标,但具有不同的优势。

使用 std 向量。 有一个包含一个月数据的结构。 输入后,将副本推回向量。