dinhvan2804
dinhvan2804

Reputation: 93

How to read specific line of file using fstream?

i am a newbie in c++ and i have a problem. i am studying about fstream. I have a data.txt file have content like this

  [exe1]
   1 0 2 9 3 8 4 7 5 6
[exe2]
   1 0 2 9 3 8 4 7 5 6:0
[exe3]
   23
[exe4]
   Micheal

My question is how can i read a specific line, like line number 2 :

1 0 2 9 3 8 4 7 5 6.

Thanks in advance

Upvotes: 0

Views: 1518

Answers (1)

marcinj
marcinj

Reputation: 49976

If the only way to find your line is searching some data in it, then you will have to read each line until the one of interest is found:

std::ifstream fs("data.txt");
std::string line;
while(std::getline(fs, line)) {
   if ( line.find("[exe2]") != std::string::npos )
   {
     if ( std::getline(fs, line) ) {
       // line found
       // line should contain "1 0 2 9 3 8 4 7 5 6:0"
       break;
     }
    }
}

Upvotes: 5

Related Questions