Getting the nth line of a text file in C++

MrJackV picture MrJackV · Sep 1, 2011 · Viewed 13.1k times · Source

I need to read the nth line of a text file (e.g. textfile.findline(0) would find the first line of the text file loaded with ifstream textfile). Is this possible? I don't need to put the contents of the file in an array/vector, I need to just assign a specific line of the text file to a varible (specifically a int).

P.S. I am looking for the simplest solution that would not require me to use any big external library (e.g. Boost) Thanks in advance.

Answer

Armen Tsirunyan picture Armen Tsirunyan · Sep 1, 2011

How about this?

std::string ReadNthLine(const std::string& filename, int N)
{
   std::ifstream in(filename.c_str());

   std::string s;
   //for performance
   s.reserve(some_reasonable_max_line_length);    

   //skip N lines
   for(int i = 0; i < N; ++i)
       std::getline(in, s);

   std::getline(in,s);
   return s; 
}