|
-
Apr 17th, 2000, 07:35 PM
#1
Hi there,
Hopefully this should be straight forward and I'm using the right terminology.
I have an ASCII text file with many quotes, each new quote on a new line and un-numbered. I want to program a little random quote grabber. I can figure all except for the most elegant way to randomly pick a line. I'm eventually going to add some animation (of this guy who says these things...which are way out), but I think I'll find what I need here or many if I'm lucky in my You Can Learn VB5 book.
Any help on this one? Email me if you could. Thanks
-
Apr 17th, 2000, 07:46 PM
#2
Addicted Member
How about opening the file and reading the entire contents into a string? Now if you are using VB6 you can use the Split function to seperate the string on the Newline characters (vbCrLf) and place all of your quotes into elements of an array. If you're not using VB6 then you'll have to write a function that uses InStr and Mid to parse the string the same way. After you have all your quotes in an array you can use the Randomize and Rnd calls to randomaly generate a number based on the UBound of the array. You can then use that number to retrieve the random quote form the array.
Lost? If you want me to elaborate with some code just post a reply specifying which version of VB you are using.
-
Apr 17th, 2000, 08:24 PM
#3
Fanatic Member
If you are opening the text file as a TextStream Object then you could try this.
First off you need to know how many lines are in the text file. Now generate a random number between 1 and the number of lines.
Now do this.
Code:
'open a text stream object
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile("c:\testfile.txt", ForReading)
'loop to the required line
For i = 1 To randomNumber
f.SkipLine
Next i
'read the line into a string
myString = f.ReadLine
'close the text file.
f.Close
Hope this helps.
Iain, thats with an i by the way!
-
Apr 17th, 2000, 09:05 PM
#4
Code:
Dim sTemp As String, arrTemp() As String, lQuote As Long, sQuote As String
Open "quotes.txt" For Input As #1
sTemp = Input(LOF(1), 1)
Close #1
arrTemp = Split(sTemp, vbCrLf)
Randomize
lQuote = cLng((ubound(arrtemp) - lbound(arrtemp) + 1) * Rnd + lbound(arrtemp))
sQuote = arrTemp(lQuote)
[Edited by matthewralston on 04-18-2000 at 10:07 AM]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|