How can I pass .txt file to an array?

Write a program that asks the user for the name of a file. The program should display the last 10 lines of the file on the screen (the "tail" of the file). If the file has fewer than 10 lines, the entire file should be displayed, with a message indicating the entire file has been displayed.

The content of Payroll.txt

1#23400
4#17000
5#21000
6#12600
9#26700
10#18900
11#18500
13#12000
15#49000
16#56500
20#65000
21#65500
22#78200
23#71000
24#71100
25#72000
30#83000
31#84000
32#90000

The above is a homework assignment that I have to complete.

I have successfully achieved getting an output of all the data. However, I cannot figure out how to only print the last 10 lines of data. I believe that passing everything into a string array is the solution. This way I can just limit which lines are printed out. The only problem is that I cannot figure out how to do this. I have tried everything that I can think of and I get the program to without any errors but there is no output. Please help.

Here is what I have


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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

bool openFile(fstream &, string);
void showContents(fstream &);

int main()
{
    string fileName;
    int size = 0;

    fstream inFile;

    cout << "Enter the file name: ";
    cin >> fileName;

    if(openFile(inFile, fileName))
    {
        cout << "File opened successfully.\n";
        showContents(inFile);
        inFile.close();
    }
    else
        cout << "File open error!" << endl;
    return 0;
}

bool openFile(fstream &file, string name)
{
    file.open(name.c_str(), ios::in);
    if(file.fail())
        return false;
    else
        return true;
}

void showContents(fstream &file)
{
    string line;
    int i = 0;
    int count = 0;

    while(file >> line)
    {
        cout << line << endl;
        count++;   //this would be the size of my array
    }
}
One way is to count the lines in the file first. The second time you skip all but the last 10 lines and display the rest.
Of course the easiest way would be to read all the lines into a vector, but I am not sure if you are allowed to use vectors.
Yes we are allowed to use vectors I'll give it try and see if I can get it to work. Thanks
Topic archived. No new replies allowed.