1

this my code but i get infinite loop with the first number
I want to read the integers fromt he file and store them in the array

the file contains:

8 5 12 1 2 7

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{    
    int n = 0; //n is the number of the integers in the file ==> 12
    int num;
    int arr[100];

    ifstream File;
    File.open("integers.txt");
    while(!File.eof())
    {
        File >> arr[n];
        n++;
    }

    File.close();

    for(int i=0;i<12;n++)
    {
        cout << arr[i] << " ";
    }

    cout << "done\n";
    return 0;
}

Any help please

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Error-F
  • 53
  • 1
  • 1
  • 8

2 Answers2

5

I agree with @ravi but I some notes for you:

If you don't know how many integers are in the file and the file contains only integers, you can do this:

std::vector<int>numbers;
int number;
while(InFile >> number)
    numbers.push_back(number);

You need to #include<vector> for this.


it would be better if you read how many integers are in the file and then use loop to read them:

int count;
InFile >> count;
int numbers[count];       //allowed since C++11

for(int a = 0; a < count; a++)
    InFile >> numbers[a];

Note: I didn't check for successful read, but it is a good practice to do so.

Quest
  • 2,764
  • 1
  • 22
  • 44
3

Your loop should be:-

for(int i=0; i < n ; i++)
{
    cout << arr[i] << " ";
}
ravi
  • 10,994
  • 1
  • 18
  • 36