Get line x from a file

How would I write the function to get line x from a file?

It should act like this:

1
2
3
4
5
char name[30]

file = "a_file.txt"

name << line(x) from "a_file"

To read the Nth line from a file (1-based), open the file and use getline() N times. The
last time you call it it will read the Nth line of text.
ok thanks. This is what I got and it seems to work. Im still very confused about whats going on but at least I have code that works.
Thank you Jsmith

#include <iostream>
#include <fstream>

using namespace std;
int i;
int x=5;

class text
{
    public:
        char zz[5];
}; // word

text word[20];

int main()
{
   ofstream a_file ( "txt.txt" );
   for (i=0;i<20;i++)
   {
        x+=i;
        a_file << (x) << endl;
   }
ifstream b_file("txt.txt");
    for(i=0;i<20;i++)
        {b_file >> word[i].zz;}

    for (i=0;i<20;i++)
        {cout << word[i].zz << endl;}
}

Last edited on
It so happens that you have only one thing per line of the file.
However, you could have more than one. Use getline().

myfile.txt
1 This is the first time
2 This is the second line
3 This is the third rhyme
4 This is the one to find
5 Out of the counting dime
myprog.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

const int LINE_TO_FIND = 4;

int main()
{
    string line;
    ifstream f( "myfile.txt" );
    for (int i=0; i<LINE_TO_FIND;i++)
    {
        getline(f,line);
    }
    cout<<"The fourth line is:\n" << line << endl;
    return 0;
}

You may also want to check that you actually read as many lines as the loop went. So to check to see if you have reached EOF or not, change line 17 to read:
1
2
    if (!f.eof()) cout<<"The fourth line is:\n" << line << endl;
    else          cout<<"There aren't that many lines in the file.\n";

Hope this helps.
Thank Duoas. Your code is much better than mine. I had looked at the reference files on getline but didn't know how to make it work with ifstream. I was just happy to have a something that could worked for this one program.
Topic archived. No new replies allowed.