2012-12-18 78 views
3

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

这里是我的代码:

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; 
} 
+4

你试过在调试器中运行它吗? – anishsane

+0

您确定这是您的确切代码吗?我只是试了一下,它的工作。 – BoBTFish

+0

无限循环?你的代码每个循环最多可产生10000次迭代... – Geoffroy

回答

2

首先,你应该使用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变量,以从文件中读取的项目数。

+0

1.你不知道所有的员工ID是分开的行;原始代码将在空间分离时起作用。 (你可以给'std :: getline一个不同的分隔符,我想)。 2.这并没有回答这个问题(虽然不错的做法可以帮助避免愚蠢的错误)。虽然我同意'std :: vector'通常是一个好主意,即使大小总是固定的,在这种情况下,调用['reserve']将会是一个好主意(http://en.cppreference.com/ w/cpp/container/vector/reserve)来避免大量重新分配。 – BoBTFish