d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > C++ Hangman Game > Read A Specific Line In A Txt File?
Add Reply New Topic New Poll
Member
Posts: 3,357
Joined: Aug 16 2008
Gold: 0.00
Jul 22 2012 08:42pm
In c++:
Wondering if there's a way to read a specific line in my text file that contains words for my hangman game
i was thinking of something along the lines of generating a random number say '5', then passing it as a parameter
to the compiler and then it would read line # 5 of the file and then store it into my string variable.

got most of my program complete but this part got me stumped.
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Jul 22 2012 08:55pm
if it's easier, just read every line one-by-one until you reach the nth line. it's usually a much more common request, so you'd be more familiar with the libraries.

there should be libraries for file pointers to go directly to a certain spot in a file. text files are unicode which means all characters take the same amount of disk space, so it should be simple to calculate offsets for the nth character. there's nothing magical about the newline character, so you can't magically jump to it. you would have to read every character one by one to see if it's a newline. if you order your text file from shortest words to longest, on the other hand, then you can be a bit more nifty and skip reading characters. i've never done it before, so i could be wrong. but i wouldn't worry about file pointers to save performance for just an amateur hangman game. stick to the easiest code which is reading whole lines until the nth line

This post was edited by carteblanche on Jul 22 2012 09:06pm
Member
Posts: 3,357
Joined: Aug 16 2008
Gold: 0.00
Jul 23 2012 04:55pm
ahh ok cool, thanks. i just found out how to do it .
Member
Posts: 1,087
Joined: May 2 2005
Gold: 75.00
Jul 24 2012 08:23am
Why not use ignore until you hit the item your after?
cin.ignore(100, '\n')
This will ignore 100 characters or until the newline is reached. You can always use something besides searching for a newline.
cin.ignore(100, 'A') ;
Member
Posts: 789
Joined: Jan 21 2006
Gold: 22.00
Jul 24 2012 10:18pm
Load all lines into an array. Call an index number.
Member
Posts: 4,790
Joined: Jun 20 2012
Gold: Locked
Trader: Scammer
Jul 26 2012 09:44pm
Quote (koa_wolf @ Jul 24 2012 09:18pm)
Load all lines into an array. Call an index number.


nice dirty trick if you dont wanna change everything!
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll