Hi guys,

I'm trying to find a way to read a chosen line from a text file. Like I want to read line 2 and then the program will find the second text line for me to read. Any tips? :)

Read the file sequentially from beginning to end, counting lines as you go along. If you want to read the 2d line then you will have to read lines 1 and 2. It is not possible to skip to a specific line in a text file.

Here is one possible way:

int i = 0;
int line = 0;
int number = 0;
char c = '\0';
string temp;

//Make sure your file is opened in binary mode when manipulating file pointers
infile.open("C:\\Documents\\test.txt", ifstream::binary);

cout << "Enter line number to read from file: ";
cin >> number;

//Search character by character for new line
//Increment counter when "new lines" are found.
do{
     infile.get(c);
     i++;
     if(c == '\n')
          line++;
     }while(line != number && infile.good());

//Set 'get' ponter to beginning of desired line to read
infile.seekg((i+1), ios:beg);

//Get the line.
getline(infile, temp);

Like ancient dragon says, there is no real automatic way to find where you want to be in the file without reading your way through it. Unless you already no exactly how many characters each line contain, and they all will always contain the same about of characters at all times, then you can just seekg() to the specific line.. but this is a very rare case.

Edited 7 Years Ago by Clinton Portis: n/a

Comments
educational helpful

Thank you guys and especially you Clinton, your code comments are really great.

This article has been dead for over six months. Start a new discussion instead.