c++ - 将数据文件读入数组

标签 c++ arrays loops text-files

我正在尝试读取一个文本文件并将其存储在一个数组中,但我的程序一直陷入无限循环。

这是我的代码:

int main () {
    const int size = 10000; //s = array size
    int ID[size];
    int count = 0; //loop counter
    ifstream employees;

    employees.open("Employees.txt");
    while(count < size && employees >> ID[count]) {
        count++;
    }

    employees.close(); //close the file 

    for(count = 0; count < size; count++) { // to display the array 
        cout << ID[count] << " ";
    }
    cout << endl;
}

最佳答案

首先,您应该使用 std::vector<int> ID;而不是原始 int数组。

其次,您的循环应该更像这样:

std:string line;
while(std::getline(employees, line)) //read a line from the file
{
    ID.push_back(atoi(line.c_str()));  //add line read to vector by converting to int
}

编辑:

你上面代码中的问题是这样的:

for(count = 0; count < size; count++) { 

您正在重复使用之前使用的计数变量来计算您从文件中读取的项目数。

应该是这样的:

for (int x = 0;  x < count; x++) {
   std::cout << ID[x] << " ";
}

这里您使用的是 count打印从文件中读取的项目数的变量。

关于c++ - 将数据文件读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13929430/

相关文章:

c++ - 使用 vector push_back 代码创建对象拷贝时遇到问题

c++ - 为什么在重载的 ostream 运算符中引用 lambda 中的 vector 会导致错误?

c++ - Conan 包从官方仓库迁移到本地私有(private)仓库

javascript - 更改数组而不链接引用

Python:将矩阵 reshape 为特定形式的向量

vba - VBA 新增功能 - 运行时错误 6,脚本在空白单元格处停止而不是循环

c++ - 如何使用c语言在framebuffer中绘制图形..?

c# - 所有数组槽都包含最后一个结果

matlab - For 循环从结构中提取信息不起作用?

python - 在一个循环中对列表的列表进行索引