Counter returning 1 more than expected

This code counts all the names on a file. There are 26 names in the file, all on separate lines. However, the counter returns 27.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    vector <string> names(0);
    string reader;
    int counter=0;

    ifstream file;
    file.open("Names.txt");

    while (getline(file, reader))
    {
        counter++;
    }
    cout << counter;
    
    return 0;
}
Last edited on
Presumably there is an empty line in the file, probably at the end.

If you're on linux or mac try running wc on the file in a terminal. How many lines does it say there are?
Yeah you were right there was an extra blank line at the end, thank you.
Topic archived. No new replies allowed.