-> I was wondering if anyone knows how to make a program read a random
-> line out of a text file.
Well, it could be done in a couple of ways. One would be to open the
file and count how many lines are in it. You'd just INPUT a line,
increment a counter, then if EOF hasn't been reached go back and INPUT
another one. When you get to EOF, close the file. Now generate a random
number between 1 and the number of lines. Re-open the file, and INPUT as
many lines as the random number, discarding all the lines except the
last one. The last one is the one you want.
The other method would be to read the whole file into a string array,
using one element of the array for each line. Then pick an element at
random. This method would require a lot of memory if the file is long,
but it would be faster than the first one, especially if you want to
pick a lot of random lines. The file would have to be read only once.
dow
--- PCBoard (R) v15.3 (OS/2) 5
---------------
* Origin: FidoNet: CAP/CANADA Support BBS : 416 287-0234 (1:250/710)
|