[cs13001] Getline() in file i/o

Mikhail Nesterenko mikhail at cs.kent.edu
Thu Mar 21 15:46:04 EDT 2013


> 
> Professor Mikhail Nesterenko,
> 
> 
> 
> I have a text.txt file which has a couple thousand lines. I need to
> access certian lines by their position in the file.
> 
> example:
> 
> 
> line 1 :hello world
> line 2 :Hello earth
> ~break
> line 123:This world
> 
> 
> How could I use getline() to access line 123?

well, if you do not know the length of each string, the easiest would
be to use a getline(). For example, write this function


   void skipLines(ifstream& myFileStream, int numLinesToSkip){
   	  string skipString;
     	  for(int i=0; i < numLinesToSkip; i++)
     	      getline(myFileStream, skipstring);
   }

If you know the length of each string. For example, if strings are all
the same length, then you can use positioning function seekg(). 
For examle:

   void skipLines(ifstream& myFileStream, int numLinesToSkip){
   	const int stringLength = 80; 
	myFileStream.seekg(stringLength*numLinesToSkip);
   }

Thanks,
-- 
Mikhail


More information about the cs13001 mailing list