Thread: need some help cleaning code up

  1. #1
    Unregistered
    Guest

    Question need some help cleaning code up

    I have wrote a code for a hangman game which is now compiling and running, only two questions to complete it.
    Firstly when it compiles it is running the first printf statement twice each times:
    eg instead of choose a letter:
    it is running chose a letter: choose a letter:
    i have looked over the code and am unable to understand why this is.
    Secondly my search function dioesnt seem to be positioning the letters in there correct place. When a letter is in the word it is saying it was found and printing the array of ----- but not placing the letter into it.
    Any suggestions how to fix this?

    #include <stdio.h>

    #define letters 5

    int search(const char list[], int letternum, char letter);

    int main(void)
    {
    char word[letters] = {'m','o', 'u', 's', 'e'};
    char guess_word[letters] = {'-','-','-','-','-'};
    char letter;
    int location;


    while (guess_word !=word)
    {
    printf("choose a letter: ");
    scanf("%c", &letter);


    location = search(word, letters, letter);

    if (location >-1)
    {
    printf("%c was found\n", letter);
    for (int i = 0; i<5; i++)
    printf("%c ", guess_word[i]);
    }
    else printf("%c was not found\n", letter);
    }
    printf("%c \n MOUSE FOUND!! YOU WIN");

    return 0;
    }

    int search(const char guess_word[], int letternum, char letter)
    {
    int i=0, found;
    found=0;
    while ( i<5 && !found)
    { if (guess_word[i] ==letter)
    found= 1;
    else i++;
    }
    if (found) return i;
    else return -1;
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    while (guess_word !=word)
    should be
    while ( strcmp ( guess_word, word ) != 0 )

    You can't compare two strings/arrays with the == operator, the strcmp function in string.h should be used if you want the program to work as you intend.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Explain this C code in english
    By soadlink in forum C Programming
    Replies: 16
    Last Post: 08-31-2006, 12:48 AM
  2. Updated sound engine code
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 11-18-2004, 12:38 PM
  3. Cleaning up my code
    By LiKWiD in forum C++ Programming
    Replies: 16
    Last Post: 07-07-2003, 08:52 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM