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

1 に答える 1

2

まず、生配列のstd::vector<int> ID;代わりに aを使用する必要があります。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変数を使用して、ファイルから読み取ったアイテムの数を出力しています。

于 2012-12-18T09:13:13.493 に答える