Printing a random question from a file

This is a discussion on Printing a random question from a file within the C Programming forums, part of the General Programming Boards category; I'm writing a program that outputs a random question from a file. In the file, I have each question numbered ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    33

    Printing a random question from a file

    I'm writing a program that outputs a random question from a file. In the file, I have each question numbered like this 1-5:

    1 Question
    multiple choices...

    2 Question
    multiple choices...

    etc.

    How can I use "random" so the program can jump to that number and print out only that question?

    Code:
    #include <stdio.h>
    #define DATAFILE "/home/usr/trivia"
    
    
    int main(){
       FILE *data = fopen(DATAFILE, "r");
       if(data == NULL){
          puts("File not found");
          return 0;
       }  
       srand(time(NULL));
       int random = rand() % 5 + 1;
       char text[1000];
       int i, j;
       while(fgets(text, 1000, data) != NULL){
             printf("%s", text);
       }
       puts("");
       fclose(data);
       return 0;
    }

  2. #2
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    I would have the user enter the number, then take in lines from input until you've reached the specified line number. No need to keep actual numbers in the lines in the file.

    edit: my bad, generate a random number, then ....

    edit2: well it seems you're making a trivia game? So then if you're planning on outputting many questions, I would first read in all the questions into an array of char arrays ( list of lines ) then you could use the actual random number as the index to the array of char arrays.

    ie

    Code:
    char * lines[ MAXLINES ];
    printf( "%s" , lines[ random ] );
    Last edited by jwroblewski44; 02-13-2013 at 11:28 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A random file access question
    By Shadow20 in forum C++ Programming
    Replies: 2
    Last Post: 11-24-2011, 11:30 AM
  2. Printing random decimal numbers in a text file
    By warrick in forum C Programming
    Replies: 3
    Last Post: 03-08-2010, 09:32 AM
  3. Creating a file with random numbers question??
    By Hoser83 in forum C Programming
    Replies: 28
    Last Post: 02-16-2006, 02:11 PM
  4. Replies: 3
    Last Post: 11-03-2003, 08:55 PM
  5. question on random file access
    By ygfperson in forum C++ Programming
    Replies: 1
    Last Post: 06-16-2002, 06:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21