Reading integers from file and store them in array C++ [closed]

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.

Leave a Comment