Thread: String tokens and random lines

  1. #1
    Registered User
    Join Date
    Apr 2008

    String tokens and random lines

    For my program I have a function for a wheel of fortune program that takes a line of input from a text file. However, I need to fix it to choose a random line and to break the line up. Could someone help me do this?

    Line in text file
    Before and After%Whitney Houston Texas
    Need to break up into string(?) which is the category(Before and after) and actual word (Whitney Houston Texas)

    Thanks so much for taking the time to read this.

    /* initialize_array */
    int initialize_array(char phrase[], char puzzle[]){
    	FILE* phraseFile = NULL;
    	char filename[256];
    	int cnt = 0;
    	char word[100];
    		phraseFile = fopen("input-words.txt", "r");
    	while (!feof(phraseFile)){
    		char c = ' ';
    		fscanf(phraseFile, "%c", &c);
    		if ((int)c < 15) break;
    		if (c >= 'a' && c <= 'z') /* convert lower case to upper case */{
    			c = to_upper(c);
    		phrase[cnt] = c; /* place the solution character into the array */
    		if (c >= 'A' && c <= 'Z'){
    			puzzle[cnt] = '*';
    		else /* it's not a letter */{
    			puzzle[cnt] = c;
    		return cnt;

  2. #2
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Sydney, Australia
    Hmm, why did you NULL phrasefile ?
    Also, you didn't use filename, it would be better to get a stdin input of a filename to read in. Instead of always having a specific name for the file in the code.

    I don't know what that code is exactly doing. But if you want to pick a random line, what you can do is.

    int lines = 0;
    Read in from the file using fgetc(), now everytime c == '\n', increment the lines.

    Now srand(time(NULL));

    And then use the rand function to choose a number between and including line 0 and the maximum number of lines.

    Now read through the file again, using the randomized number as the guide, until you encounter x '\n'

    fgetc() again until the next line, copy that string into a buffer. And then strtok it.

    Not sure if this is the best way.
    Everytime you segfault, you murder some part of the world

  3. #3

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Random tokens
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 06-14-2002, 12:11 PM