Results 1 to 4 of 4

Thread: Random quote grabbing

  1. #1
    Guest

    Question

    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

  2. #2
    Addicted Member
    Join Date
    Aug 1999
    Location
    Ottawa,ON,Canada
    Posts
    217
    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.

  3. #3
    Fanatic Member
    Join Date
    Mar 2000
    Location
    That posh bit of England known as Buckinghamshire
    Posts
    658

    Lightbulb

    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!

  4. #4
    Guest
    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
  •  



Click Here to Expand Forum to Full Width