Help With Reversing from a Text File

closed account (LNAM4iN6)
I am supposed to input a file, store it into a vector, count how many numbers were stored, and then output the numbers in reverse order. The text file consists of an indeterminate amount of integers, each with their own line. For testing purposes, my text file is simply the numbers 1-15, once again each number is on it's own line. This is my code. I don't understand why my output includes the zero before the rest of the numbers. Could someone help me fix this error and explain why it is doing this? Thank you very much.
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;

int main () {

vector<int> intsFromFile;
ifstream integerfile;
string filename;
int numbers;

cout << "Please input the file you want to use: ";
cin >> filename;

integerfile.open(filename.c_str());
if (!integerfile){
cout << "File not found" << endl;
return 0;
}
while (integerfile >> numbers) {
intsFromFile.push_back(numbers);
}

cout << "Numbers read: " << intsFromFile.size() << endl;

for (int i = intsFromFile.size(); i >= 0; i--) {
cout << intsFromFile[i] << endl;
}

return 0;
}
Numbers read: 15
0
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
Given a vector of size [i], the last element is at location [i-1].

You are reading element [i], which is off the end. You're reading some garbage data that just happens to be zero.

A big clue to this is that you output 16 numbers when you thought you were only going to output 15.
closed account (LNAM4iN6)
This makes perfect sense! Thank you so much!
Topic archived. No new replies allowed.