Thread: help with random function

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    1

    Question help with random function

    i got a friend thats writing some c++ right now and he needs some help with a random function. he has a text file and it has 222 words in it but he needs to know how to make a random function that will take a number between 1 and 222 and pull the word in that line of the text file and use the word it pulled as the word. And btw hes making hangman if u need to know

    and he's using dos not a gui
    Last edited by lilfade; 12-05-2005 at 01:03 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You \b\b\b your friend should visit http://faq.cprogramming.com/cgi-bin/smartfaq.cgi and type rand into the search box.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    1) Get the random number in the proper range

    2) Use the >> operator in a while loop conditional to read in words from the file, e.g.:
    Code:
    while(inFile>>word)
    {
        ...
    }
    3) Keep looping until a loop counter reaches the random number, then break out of the loop, and 'word' will contain the word you want.
    Last edited by 7stud; 12-05-2005 at 07:04 AM.

  4. #4
    the Great ElastoManiac's Avatar
    Join Date
    Nov 2005
    Location
    Republika Srpska - Balkan
    Posts
    377
    Use <fstream>, rand() and srand()
    lu lu lu I've got some apples lu lu lu You've got some too lu lu lu Let's make some applesauce Take off our clothes and lu lu lu

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    rand() and srand() are in <cstdlib>.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Replies: 5
    Last Post: 02-08-2003, 07:42 PM