SaleenS7 SaleenS7 - 9 days ago 6
C++ Question

Using file input to input integers

I am stuck here having trouble figuring out as to why this loop is not inserting the integers from a text file into an array.

I have a textfile that contains 100 integers, all separated by spaces. I am trying to insert these integers into an array. However when I output, for example a[2], it outputs 0, leading me to believe that the numbers are not being inserted into the array.

listFile.open("unsortedlist.txt");
cout << endl << "Unsorted list = ";
for (int i = 0; i < 100; i++)
{
while (listFile >> individualNum )
{
a[i] = individualNum;
cout << individualNum << ", ";
}
}


cout << "\n" << a[1] << "\n";

Answer

The inner loop will diligently read every number from the file.

And assign every number to a[i]. The same array element, each and every time.

On the first iteration of the outer loop, i is 0, so the code will read every number from the file, assigning each number to a[0].

When the inner loop reaches the end of the file, it will terminate. Then, the outer for loop will increment i to 1, iterate again, and run the inner loop. Since the entire file has been read, the inner loop will not do anything. Neither it will do anything more, for the remaining 98 elements of the array.

The loop should probably be, simply:

for (int i = 0; i < 100; i++)
        listFile >> a[i];

Keep in mind that this will work correctly, of course, only when there are exactly 100 integers in the file.