MrJackV MrJackV - 1 year ago 87
C++ Question

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

I need to read the nth line of a text file (e.g.

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 Source

How about this?

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

   std::string s;
   //for performance

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

   return s; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download