在一个文件中循环一次,将行读取到添加到数组中的对象中
Loop through a file once, reading lines into objects added to an array
我正在阅读一个文件,其中的每一行都代表我将添加到数组中的对象。我事先不知道文件中有多少行,只能循环浏览一次。此外,我被限制使用普通数组,没有其他容器或集合类。这是我得到的:
ifstream f;
f.open("lines.csv");
string line;
string theCode;
string theName;
Manufacturer **manufacturers = new Manufacturer*[752]; // this number can't be here - I have to allocate dynamically
int index = 0;
while(getline(f, line))
{
theCode = line.substr(0, 6);
theName = line.substr(7, string::npos);
Manufacturer* theManufacturer = new Manufacturer(atoi(theCode.c_str()), theName);
manufacturers[index++] = theManufacturer;
}
每次索引到达当前数组的末尾时,都需要重新分配一个更宽的数组。就像这样。
int capacity = 752;
while(getline(f, line))
{
if (capacity <= index) {
capacity = (capacity+1) * 2;
Manufacturer **tmp = new Manufacturer*[capacity];
std::copy(manufacturers, manufacturers+index, tmp);
delete[] manufacturers;
manufacturers = tmp;
}
/* ... */;
}
相关文章:
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- 如何读取文件的内容,如果文件中的单词重复,请将它们添加到列表中?
- C++添加检查以避免读取两个参数
- C 需要帮助的作业程序,该程序在文件列表中读取并在每个双重的双重列表中添加一个字符串
- C++/CPP 读取添加的十六进制地址
- 向现有类添加一个方法以逐行读取文件的内容
- 如何添加和读取两种变量的向量元素
- 读取文件时添加操作员
- C++读取添加到目录中的新文件
- 如何将读取数据添加到数组中?
- 从文件中读取到struct并添加到向量
- C++从文件中读取并将元素添加到字符串向量
- 从txt文件中读取数字,添加一些数字,然后在c ++中将其重写为其他文件
- 单链表添加函数-读取访问冲突
- 在一个文件中循环一次,将行读取到添加到数组中的对象中
- 使用 push_back() 在向量中添加项目,向量的大小会增加但无法从向量中读取值
- C++从文本文件中读取、解析和添加价格
- C++银行项目;如何将一组字符串读取为单独的浮点数并添加它们
- 读取文件并将其添加到文本框中:字符串转换问题
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中