Read specific line from text file.

I have a text file that I would like to read a specific line from. All lines have the same amount of characters (one 3-digit number on each), and I would like to read from a specified line. Is there a way to do this?

Thanks!
Last edited on
If each line is 3 digits long you can use seekg. http://www.cplusplus.com/reference/istream/istream/seekg/
Yeah, sorry to ask, but I still don't know how to use it. I'm rather new to C++.

How would I use that to tell me the contents of that line in the form of an int (considering that each line contains a 3-digit integer)?

Thanks!
I'd suggest using getline() in a loop to read (and discard) the required number of lines to reach the required data. Then perhaps use atoi() to convert the text of the line into an int. Or use a stringstream to extract the number from the line.

http://www.cplusplus.com/reference/string/string/getline/
http://www.cplusplus.com/reference/cstdlib/atoi/
http://www.cplusplus.com/reference/sstream/istringstream/istringstream/
Alternatively, if you are certain that each line contains just a number and nothing else (apart from some possible whitespace), then forget about reading lines. Just read a number repeatedly using a loop, in order to ignore the first n-1 values.
Yeah, I'm still a bit lost as to how to do the loop thing. How am I supposed to ignore lines exactly?
So, you have a hallway with a bunch of doors numbered 1, 2, 3, ... and you want to knock on door 5. To get to door 5, you have to walk past (ignore) doors 1 through 4. What does ignore mean? Just don't knock on them!

To ignore a line, read it in but don't do anything with it.
Last edited on
You could also just do in.seekg(34*(line-1)); //or if starting at line 0 instead of 1 just multiply by line

[edit] It should probably be 4 * line-1 not 3 * because of the newline.

How would I use that to tell me the contents of that line in the form of an int (considering that each line contains a 3-digit integer)?


1
2
int number;
in >> number;
Last edited on
Well, if you're going to hard-code for the size of each line and ignore the possibility of whitespace, then I suppose that's a valid solution...but I recommend not using it.
All lines have the same amount of characters (one 3-digit number on each)
LB wrote:
and ignore the possibility of whitespace,
Seeking to an arbitrary position in a file stream opened in text mode has undefined behaviour.
(Though it works on Unix and Unix-like platforms).
Topic archived. No new replies allowed.