Reading line from a text file

I know this has been posted a million times, but I can't find one that actually solved my problem.

I want to read a line from a text file basically, but I'm not sure how to jump to the line I want

I tried the seekg() function, but I need to know the size of the previous lines to get to where I want.

1
2
3
4
5
6
7
8
9
10
11
12
string strLine;
ifstream myFile;
myFile.open("highscores.txt");
if (myFile.is_open())
{
		myFile.seekg(5);
		getline(myFile, strLine);
		cout << "output is: " << strLine;

		myFile.close();
}
//This just jumps 5 characters from the beginning of the file 


I do have an idea in my head for a function I could write myself, but surely there is already a way to do it.

Is there some kind of shortcut I can use to jump straight to a line of a text file?
I want to read a line from a text file basically, but I'm not sure how to jump to the line I want
You will need to search for the line somehow.

How do you know if you've reached your line?

Also, consider these points.
* Don't call open on an fstream.
* Don't call close on an fstream.
* Don't test if an fstream is open.
* Think of it as a sequential data stream.

Why? So you write code that works with any sequential data stream, not just files.

Your code following those rules look like:
1
2
3
4
5
6
std::string strLine;
std::ifstream myFile("highscores.txt");
while (std::getline(myFile, strLine))
{
    // use strLine
}
Last edited on
Thanks for the info. I just learned this stuff a few days ago and I guess I was just taught the basics :P I'm just trying to implement it before I forget it!

Regarding your suggestion though, how do I search for the line?
My original idea was something like adding the length of each line (before the one I wanted) to an integer, and then doing seekg() of that integer value, but I'm sure that there should be an inbuilt function to reach specific lines since it would be such a common thing.

Cheers
Last edited on
Topic archived. No new replies allowed.