Sunday, May 10, 2009

C program help?

Hello, I'm trying to simulate wheel of fortune in C. Its been years since I've used C. I need to randomly get a word from a file. How can I modify this code which just gets the first word from a text file?


int prepare_word(char word[], char puzzle[])


{


FILE* clues = NULL;


char file[200];


int numcount = 0;


char word[100];


while (!phraseFile)


{


printf("Enter the name of the file containing the secret phrase -%26gt; ");


scanf("%s", file);


// clues = fopen("d:/test.txt", "r");


clues = fopen(file, "r");


if (!clues) printf("\nSorry, I could not open %s, lets try again\n",file);


}


while (!feof(clues))


{


char c = ' ';


fscanf(clues, "%c", %26amp;c);


if ((int)c %26lt; 15) break;


if (c %26gt;= 'a' %26amp;%26amp; c %26lt;= 'z') /* convert lower case to upper case */


{


c = to_upper(c);


}


word[numcount] = c; /* place the solution character into the array */


if (c %26gt;= 'A' %26amp;%26amp; c %26lt;= 'Z')


{


word[numcount] = '*';


}


else /* it's not a letter */


{


puzzle[numcount] = c;


}


++numcount;


}


return numcount;


}

C program help?
Basically, you want to break this up into a couple of tasks:


1. Read each word from the file into an array of strings


2. Use rand() to generate a random number, and extreact that word from the array.





Step 1 is complicated by the fact that C doesn't have a very good set of string primitives. So you'll have to read each line of the file into a buffer, using fscanf(), then allocate memory for each word, based on its length, and copy the buffer into the newly allocated string.





basically (this won't compile)





/* Step 1 */


char *a[1000]; /* an array of 1000 pointers to strings */


char buffer[1024]; /* a temporary buffer */


int x=0; /* an index */


int wordcount=0; /* count of words */


while (!feof(file))


{


fscanf(file, "%s", buffer);


a[x] = malloc(strlen(buffer));


strcpy(a[x], buffer);


x++;


}


wordcount=x;





/* Step 2 */


x = rand() * worcount / RAND_MAX;


printf("Random word: %s\n", a[x]);

song downloads

No comments:

Post a Comment