Read specific line from text file.

Apr 1, 2014 at 10:04pm
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 Apr 1, 2014 at 11:32pm
Apr 1, 2014 at 10:12pm
If each line is 3 digits long you can use seekg. http://www.cplusplus.com/reference/istream/istream/seekg/
Apr 1, 2014 at 11:33pm
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!
Apr 2, 2014 at 9:11am
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/
Apr 2, 2014 at 9:25am
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.
Apr 2, 2014 at 11:31pm
Yeah, I'm still a bit lost as to how to do the loop thing. How am I supposed to ignore lines exactly?
Apr 2, 2014 at 11:33pm
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 Apr 2, 2014 at 11:34pm
Apr 2, 2014 at 11:57pm
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 Apr 3, 2014 at 12:02am
Apr 2, 2014 at 11:59pm
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.
Apr 3, 2014 at 12:00am
All lines have the same amount of characters (one 3-digit number on each)
Apr 3, 2014 at 12:03am
LB wrote:
and ignore the possibility of whitespace,
Apr 3, 2014 at 12:09am
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.