How can I read a certain part of a txt file c++

Hi,I have a txt file and this file has 9 lines in it. All lines have the same lenght. Now I want for example to read from line 5 to line 8. How can I do that?
I can put out how many lines the file has or I can find a specific line for example if I look after the word "food" and this word is in the line 4 than I can print the line number out( in this case number 4).

But my problem is that I can not read a certain part from a file. Can somebody help me with an advice or a piece of code to demonstrate me how to continue my work?

Thank your for your time
well, I would read each line into a string then process each one individually. In your case I would use code similar to the following:

1
2
3
4
5
6
7
8
9
10
11
12
ifstream fin("text.txt");
string line;

for (int i = 1; !fin.eof() ; i++)
{
  getline(fin, line);

  if (i < 5 || i >8)  continue; //Read the next line if we are not between lines 5 and 8
  

  //Do what you want with your line here;
}
Last edited on
Thank you! I will try your code right now
@Stewbond

You saved my day!! Thanky you so much!!
Any time good sir.
you can also use the while loop instead of the for loop .


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
#include <iostream>
#include <fstream>
using namespace std; 

int main()
{
    ifstream ifn("text.txt");
    string line; 
    int count = 0 ; 
    if(!ifn.is_open())
    {
       cout<<"\n Cannot open the text.txt file";
     }
     else
        {
		while( ifn.good() )
		{
		    count++;
		    getline( ifn , line); 
		    if(count < 5 || count > 8)
			continue;
		    else
		       cout<<line <<"\n";
		}

         }
}
Topic archived. No new replies allowed.