Random line in a text file. [C#],
Members - Reputation: 100
Posted 26 March 2004 - 08:28 AM
Posted 26 March 2004 - 08:43 AM
Members - Reputation: 1682
Posted 26 March 2004 - 09:45 AM
- read the file in some kind of text mode, and read a line at a time until this is no longer possible. Count up the number of lines you read as you did it.
- read the file as binary, and look at each character in turn, counting the instances of line breaks. For text files under Windows this will be a CR/LF sequence (ascii 13 followed by ascii 10); for anything else it will just be a CR (13). I think I got that right anyway. Damn windows and its bizarre CR/LF legacy >_<
Members - Reputation: 150
Posted 27 March 2004 - 12:36 PM
Original post by Anonymous Poster
Open it, read through the entire thing and record the number of line break characters. Then, just create a random number between 0 and the number of lines, and seek to that line. What exactly is the problem?
Actually, the number of lines would be the number of breaks-1, wouldn''t it?
2 breaks, 3 lines.
Moderators - Reputation: 5639
Posted 28 March 2004 - 11:56 AM
Initialise the chosen line to an empty string.
Attempt to read a line.
If you failed to read a line, you're done; return the chosen line.
This line has a one in 'counter' chance of being the line you want.
So if a random float from 0.0 to 1.0 is smaller than (1.0 / counter), store the current line as the chosen one.
Repeat from the 'attempt to read a line' part.
[ MSVC Fixes | STL Docs | SDL | Game AI | Sockets | C++ Faq Lite | Boost
Asking Questions | Organising code files | My stuff | Tiny XML | STLPort]
[edited by - Kylotan on March 28, 2004 6:57:17 PM]
Posted 04 May 2004 - 11:40 PM
but Im still a noob.,
can anybody provide an example, please.
Members - Reputation: 131
Posted 05 May 2004 - 05:04 AM
Members - Reputation: 968
Posted 05 May 2004 - 05:54 AM
Original post by EbonySeraphim
A better, and possibly slower, way might be if you read in a byte(character by character) at a time, and basically check for newline characters and count them up. I think that is the easiest way because some of the other methods may eliminate whitespaces for you and break at parts other than a new line.
Nope, ReadLine is the superior way of doing this. Your suggestion is a hack.