Reading And Randomising From File

This is a discussion on Reading And Randomising From File within the C Programming forums, part of the General Programming Boards category; Hi I am making a H A N G M A N. I have posted earlier as well. Now I ...

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    9

    Reading And Randomising From File

    Hi I am making a H A N G M A N. I have posted earlier as well. Now I have developed it roughly and would like to post it here. Please help me out on this. What Its supposed to do is Read from a file then keeps it in memory, then asks the user to guess them. Please help me on this. HELP ME PLEASE

    Code:
    #include<stdio.h>
    #include<string.h>
    #include<conio.h>
    #include<time.h>
    #include<stdlib.h>
    int func(void);
    void wrong(void);
    void hello(void);
    int main(void)
    #define MAX_WORDS    1024
    {
    typedef struct
    {
      char* m_Array [MAX_WORDS]; // Every entry is a pointer to string
      int m_iCount; // How many filled in 'm_Array'
    }
    WORDS;
    
    void CreateWords (WORDS* pWords, char* pstrFileName)
      {
      FILE* pFile = fopen (pstrFileName, "rt");
      char strLine [32]; // Assume words are no longer than 31 chars
      int iLastCharPos;
    
      if (pFile) {
        pWords->m_iCount = 0;
        while (fgets (strLine, 31, pFile)) {
          // Remove '\n', at the end, if any:
          iLastCharPos = strlen (strLine) - 1;
          if (strLine [iLastCharPos] == '\n') {
            strLine [iLastCharPos] = '\0';
            }
          pWords->m_Array [pWords->m_iCount] = strdup (strLine);
          (pWords->m_iCount)++;
          if (pWords->m_iCount == MAX_WORDS) {
            break; // Array is full
            }
          }
        fclose (pFile);
        }
      }
    
    char* GetRandomWord (WORDS* pWords)
      {
      return pWords->m_Array [rand () % pWords->m_iCount];
      }
    
    void DestroyWords (WORDS* pWords)
      {
      for (int i=0; i < pWords->m_iCount; i++) {
        free (pWords->m_Array [i]);
        }
      }
    
    
        {
        	char words[10][10] = {"mythology", "astrology", "interface", "programme", "schedules",
        	"faithless", "sandstorm", "bulgarian", "boulevard", "salvation"};
        	char temp[10] = "_________";
        	int count, random, flag;
        	char current[10];
        	char ch;
        	int i,t,q;
        	count = 50;
        	flag = 2;
    
            		strcpy(temp,"_________");
            		random=func();
    
    
                		for(q=0;q<strlen(words[random]);q++){
                			current[q]=words[random][q];
                		}
                		do
    
    
                    		{
                    			printf("\n Points left: %d ",count);
                    			printf(temp);
                    			ch=getch();
                    			flag = 2;
                    			for(t=0;t<strlen(current);t++)
    
    
                        			{
                        				if(ch==current[t])temp[t]=ch;
                        				flag=0;
                        			}
                        			if(flag<2)count--;
    
    
                            			if(count<1){
                            				wrong();
                            				return 0;
                            			}
                            		}
    						        
    	        while(strcmp(temp,words[random]));
          		printf("\nYou did it. \nPress any key to exit...");
          		ch=getche();
    
               	return 0;
             }
    
    }
    
    
            int func(void){
               	srand((unsigned)time(NULL));
               	return (int)rand()%10;
            }
    
    
          void wrong(void)
    		{
               	printf("\n\nSorry, But You Have Run Out Of Your Tries. Please Retry The Program");
            }

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Don't you need a main() somewhere???

  3. #3
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    he has a main, you just missed it cause he has a preprocessor statement after it.

    Dude you posted this exact code on another forum. As they told you there, your not gonna get a response unless you tell us what your problem is. And I think I already made a suggestion as well.

    not to mention, i think there are rules on this forum about double posting.

  4. #4
    Registered User
    Join Date
    Apr 2004
    Posts
    9

    Program Developed

    Hi, The Program has been modified now and can compile but gives the following error: (120) : error C2065: 'clrscr' : undeclared identifier. I would like to know why its giving this and also What Is The Format For Entering The Words into The TextFile And How Many Times Do I Call It And Where. Thanks Alot.

    Here Is The Code:

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    #include <conio.h>
    #include <time.h>
    #include <stdlib.h>
    
    int  func (void);
    void wrong (void);
    void hello (void);
    
    #define MAX_WORDS    1024
    
    struct _WORDS
    {
      char* m_Array [MAX_WORDS];	// Every entry is a pointer to string
      int	m_iCount;		// How many filled in 'm_Array'
    };
    typedef struct _WORDS WORDS;
    
    void
    CreateWords (WORDS* pWords, char* pstrFileName)
    {
    	FILE*	pFile;
    	char	strLine [32];	// Assume words are no longer than 31 chars
    	int	iLastCharPos;
    
    	pFile = fopen (pstrFileName, "rt");
    	if (!pFile) {
    		fprintf (stderr, " Error: Couldn't open file `%s'!\n", pstrFileName);
    	}
    	else {
    		pWords->m_iCount = 0;
    		while (fgets (strLine, 31, pFile)) {
    			// Remove '\n', at the end, if any:
    			iLastCharPos = strlen (strLine) - 1;
    			if (strLine [iLastCharPos] == '\n')
    				strLine [iLastCharPos] = '\0';
    
    			pWords->m_Array [pWords->m_iCount] = strdup (strLine);
    			(pWords->m_iCount)++;
    			if (pWords->m_iCount == MAX_WORDS)
    				break;		// Array is full
    		}
    		fclose (pFile);
    	}
    }
    
    char*
    GetRandomWord (WORDS* pWords)
    {
    	return pWords->m_Array [rand () % pWords->m_iCount];
    }
    
    void
    DestroyWords (WORDS* pWords)
    {
    	for (int i=0; i < pWords->m_iCount; i++)
    		free (pWords->m_Array [i]);
    }
    
    int
    main (int argc, char *argv[])
    {
    	/*
    	char words[10][10] = {"mythology", "astrology", "interface",
    			      "programme", "schedules", "faithless",
    			      "sandstorm", "bulgarian", "boulevard", "salvation"};*/
    	char	*temp;
    	WORDS	words;
    
        	int	count;
    	int	random;
    	int	flag;
    
        	char	*current;
    	char	*inserted;	// That's where the already inserted letters are
    				// stored
    	char	*solution;	// Give user a whole try -> premature end
        	char	ch;
        	int	i, t, q;	// Why don't reduce them to one?
    	bool	finished;
    
        	// count = 50;		// Hell, how many letters do we have? Around 26 ...!?
    	count = 10;		// It would be more logic, if we put down tries to 10
    				// Better: 7/8
    	finished = false;
        	flag = 2;
    
    	temp     = (char*) malloc (sizeof (char) * 32);
    	current  = (char*) malloc (sizeof (char) * 32);
    	inserted = (char*) malloc (sizeof (char) * count);
    	solution = (char*) malloc (sizeof (char) * 32);
    
    	if (argc < 2) {
    		fprintf (stderr, "Need filename as argument!\n");
    		return 0;
    	}
    	CreateWords (&words, argv[1]);
    
    	srand (time (0));
    	
    	while (!finished) {
    		current = GetRandomWord (&words);
    		memset (temp, '_', strlen (current));
    		temp[strlen (current)] = '\0';
    		memset (inserted, 0, 32);
    		memset (solution, 0, 32);
    
    		/*
            	random = func();
    
    		for (q=0; q<strlen (words[random]); q++)
    			current[q] = words[random][q];
    		*/
    
    		while (true)
    		{
    		loop_begin:
    			clrscr ();
    			printf ("\n               --- Hangman ---\n");
    			printf ("                                  Tries left: %d\n\n", count);
    			printf (" Word: %s \n"
    				"                                  Wrong Guessed:\n"
    				"                                  --------------\n"
    				"                                  %c %c %c %c %c\n"
    				"                                  %c %c %c %c %c\n",
    				temp, inserted[0], inserted[1], inserted[2], inserted[3],
    				inserted[4], inserted[5], inserted[6], inserted[7],
    				inserted[8], inserted[9], inserted[9]); 
    			if (strcmp (temp, current) == 0) {
    				printf("\nYou did it. \nPress any key to continue ...");
    				break;
    			}
    			ch = tolower (getch ());
    			
    			if (ch == '?')
    				goto end;
    			else if (ch == '!') {
    				printf ("\n Solution: ");
    				scanf ("%s", solution);
    
    				if (strcmp (solution, current) == 0)
    					printf (" That's right!\n");
    				else {
    					printf (" That's wrong!\n");
    					printf (" Right answer was: %s\n", current);
    				}
    
    				break;
    			}
    			if (!isalpha (ch))
    				goto loop_begin;
    
    			// if already inserted, skip the following
    			for (t=0; t<strlen (inserted); t++)
    				if (ch == inserted[t])
    					goto loop_begin;
    
    			flag = 0;
    			for (t=0; t<strlen (current); t++)
    				if (ch == tolower (current[t])) {
    					temp[t] = current[t];
    					flag = 2;
    				}
    
    			if (flag < 2) {
    				count--;
    				inserted[strlen (inserted)] = ch;
    			}
    
    			if (count <= 1) {
    				wrong ();
    				return 0;
    			}
    		}
    
    		ch = getche();
    	}
    
    end:
    	free (temp);
    	free (current);
    	free (inserted);
    	free (solution);
    	DestroyWords (&words);
    
    	return 0;
    }
    
    int
    func (void)
    {
    	return (int) rand() % 10;
    }
    
    void
    wrong (void)
    {
    	printf ("\n\nSorry, But You Have Run Out Of Your Tries. Please Retry The Program");
    }

  5. #5
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    clrscr is windows specific linux doesn't have it. you could do system("clear");
    I didn't understand your second question

  6. #6
    Registered User
    Join Date
    Apr 2004
    Posts
    9
    I tried system("clear"); and compiled and linked but exited at run. My second question was that as this program is suppose to read from a file and read words and randomise them, How can I setup the text file with words it suppose to read, and special requirements for them? Thanks


    Quote Originally Posted by linuxdude
    clrscr is windows specific linux doesn't have it. you could do system("clear");
    I didn't understand your second question

  7. #7
    Registered User
    Join Date
    May 2004
    Posts
    22

    Linux compiling

    on linux unless whole program is bug free , you cant run the program to perfection. I suggest you use gdb to trace errors in your code.

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I stopped reading when I saw a label in the code...
    Code:
    end:
    Of course, I was reading up from the bottom at the time, or I'd have seen the goto, which would have made me cry.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,822
    What the hell, you ignored every single point I made, not much point in saying anything is there.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    Registered User
    Join Date
    Apr 2004
    Posts
    9
    This program compiles and runs now, All I want to know now how can I insert the filename C:\My Documents\Hangman\words.txt in the code so it read words from the words.txt and makes the hangman game work. Here is the code:


    Code:
      
    
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    #include <conio.h>
    #include <time.h>
    #include <stdlib.h>
    
    int  func (void);
    void wrong (void);
    void hello (void);
    void
    clrscr (void);
    
    #define MAX_WORDS    1024
    
    struct _WORDS
    {
      char* m_Array [MAX_WORDS];	// Every entry is a pointer to string
      int	m_iCount;		// How many filled in 'm_Array'
    };
    typedef struct _WORDS WORDS;
    
    void
    CreateWords (WORDS* pWords, char* pstrFileName)
    {
    	FILE*	pFile;
    	char	strLine [32];	// Assume words are no longer than 31 chars
    	int	iLastCharPos;
    
    	pFile = fopen (pstrFileName, "rt");
    	if (!pFile) {
    		fprintf (stderr, " Error: Couldn't open file `%s'!\n", pstrFileName);
    	}
    	else {
    		pWords->m_iCount = 0;
    		while (fgets (strLine, 31, pFile)) {
    			// Remove '\n', at the end, if any:
    			iLastCharPos = strlen (strLine) - 1;
    			if (strLine [iLastCharPos] == '\n')
    				strLine [iLastCharPos] = '\0';
    
    			pWords->m_Array [pWords->m_iCount] = strdup (strLine);
    			(pWords->m_iCount)++;
    			if (pWords->m_iCount == MAX_WORDS)
    				break;		// Array is full
    		}
    		fclose (pFile);
    	}
    }
    
    char*
    GetRandomWord (WORDS* pWords)
    {
    	return pWords->m_Array [rand () % pWords->m_iCount];
    }
    
    void
    DestroyWords (WORDS* pWords)
    {
    	for (int i=0; i < pWords->m_iCount; i++)
    		free (pWords->m_Array [i]);
    }
    
    int
    main (int argc, char *argv[])
    {
    	/*
    	char words[10][10] = {"mythology", "astrology", "interface",
    			      "programme", "schedules", "faithless",
    			      "sandstorm", "bulgarian", "boulevard", "salvation"};*/
    	char	*temp;
    	WORDS	words;
    
        	int	count;
    	int	random;
    	int	flag;
    
        	char	*current;
    	char	*inserted;	// That's where the already inserted letters are
    				// stored
    	char	*solution;	// Give user a whole try -> premature end
        	char	ch;
        	int	i, t, q;	// Why don't reduce them to one?
    	bool	finished;
    
        	// count = 50;		// Hell, how many letters do we have? Around 26 ...!?
    	count = 10;		// It would be more logic, if we put down tries to 10
    				// Better: 7/8
    	finished = false;
        	flag = 2;
    
    	temp     = (char*) malloc (sizeof (char) * 32);
    	current  = (char*) malloc (sizeof (char) * 32);
    	inserted = (char*) malloc (sizeof (char) * count);
    	solution = (char*) malloc (sizeof (char) * 32);
    
    	if (argc < 2) {
    		fprintf (stderr, "Need filename as argument!\n");
    		return 0;
    	}
    	CreateWords (&words, argv[1]);
    
    	srand (time (0));
    	
    	while (!finished) {
    		current = GetRandomWord (&words);
    		memset (temp, '_', strlen (current));
    		temp[strlen (current)] = '\0';
    		memset (inserted, 0, 32);
    		memset (solution, 0, 32);
    
    		/*
            	random = func();
    
    		for (q=0; q<strlen (words[random]); q++)
    			current[q] = words[random][q];
    		*/
    
    		while (true)
    		{
    		loop_begin:
    			system ("cls");
    			printf ("\n               --- Hangman ---\n");
    			printf ("                                  Tries left: %d\n\n", count);
    			printf (" Word: %s \n"
    				"                                  Wrong Guessed:\n"
    				"                                  --------------\n"
    				"                                  %c %c %c %c %c\n"
    				"                                  %c %c %c %c %c\n",
    				temp, inserted[0], inserted[1], inserted[2], inserted[3],
    				inserted[4], inserted[5], inserted[6], inserted[7],
    				inserted[8], inserted[9], inserted[9]); 
    			if (strcmp (temp, current) == 0) {
    				printf("\nYou did it. \nPress any key to continue ...");
    				break;
    			}
    			ch = tolower (getch ());
    			
    			if (ch == '?')
    				goto end;
    			else if (ch == '!') {
    				printf ("\n Solution: ");
    				scanf ("%s", solution);
    
    				if (strcmp (solution, current) == 0)
    					printf (" That's right!\n");
    				else {
    					printf (" That's wrong!\n");
    					printf (" Right answer was: %s\n", current);
    				}
    
    				break;
    			}
    			if (!isalpha (ch))
    				goto loop_begin;
    
    			// if already inserted, skip the following
    			for (t=0; t<strlen (inserted); t++)
    				if (ch == inserted[t])
    					goto loop_begin;
    
    			flag = 0;
    			for (t=0; t<strlen (current); t++)
    				if (ch == tolower (current[t])) {
    					temp[t] = current[t];
    					flag = 2;
    				}
    
    			if (flag < 2) {
    				count--;
    				inserted[strlen (inserted)] = ch;
    			}
    
    			if (count <= 1) {
    				wrong ();
    				return 0;
    			}
    		}
    
    		ch = getche();
    	}
    
    end:
    	free (temp);
    	free (current);
    	free (inserted);
    	free (solution);
    	DestroyWords (&words);
    
    	return 0;
    }
    
    int
    func (void)
    {
    	return (int) rand() % 10;
    }
    
    void
    wrong (void)
    {
    	printf ("\n\nSorry, But You Have Run Out Of Your Tries. Please Retry The Program");
    }
    Last edited by HelpMePlease; 05-23-2004 at 02:22 PM.

  11. #11
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    520
    if you keep the words in a text file, users could easily open it and then have an easier time guessing the words, unless there was like 2000 words in there, but they could still use a search function or something.... :P

    Though this is probably a homework assignment, so it doesnt really matter then.

  12. #12
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    unsubscribed from this thread.

  13. #13
    Registered User
    Join Date
    Apr 2004
    Posts
    9

    Thumbs down Ok

    Quote Originally Posted by caroundw5h
    unsubscribed from this thread.
    OK Whatever That Means

Popular pages Recent additions subscribe to a feed

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