如何存储未知次数迭代的输入?
How to store input for an unknown number of iterations?
我正在为循环的学校项目编写一个问题。
该程序是一个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 向量。 有一个包含一个月数据的结构。 输入后,将副本推回向量。
相关文章:
- 如何存储未知次数迭代的输入?
- 从 C++ 中的标准输入迭代读取字节
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 当迭代器(输入参数)通常不是constexpr时,constexpr算法真的有用吗
- 如何从高性能的输入迭代器返回变体?
- 如何实现构造函数,使其仅接受使用 typeid 的输入迭代器?
- 输入迭代器是否可以仅在赋值的右侧符号上取消引用?
- 输入迭代器的相等性比较
- 取消引用的输入迭代器的地址?istream_iterator的情况
- 为什么输入迭代器在递增后会使自身失效?
- 迭代器作为C 中的函数输入
- 从 std::copy 和 std::copy_n 中提取输入迭代器
- 输入迭代器 - 星号和后缀运算符
- 如何在没有原因(有输入)的情况下修复迭代;在 c++ 中?
- 如何调整我的代码以确保我的迭代代码接受用户输入
- 输入迭代器可以重复读取,而输出迭代器只能写入一次
- 使用输入迭代器再次遍历容器
- 创建不存储value_type的输入迭代器
- 输入迭代器的示例`end()`实际上表示一个past-end-end
- 输入迭代器必须具有常量解引用运算符吗