如何在C语言中完善hangman循环问题?

时间:2014-12-25 14:24:44

标签: c

挂人有问题请说明一下? 键入代码时显示的字母“未找到”并且必须键入两次相同的字母才能接受?并且猜测这封信的可能性会减少如何修复它?

#include <stdio.h>
  #include <stdlib.h>
  #include <string.h>                 
  #include <time.h>
  #include <ctype.h>

   #define WORD_COUNT 3
   #define MAX_LENGTH 10

   typedef char string[MAX_LENGTH];

   void main(void) {

       string words[WORD_COUNT] = { "bird","fish","lion","ants","bear","deer","fowl" };

       char answer[MAX_LENGTH];
       char guess;
       int count = -0, index, i, found, choice = -7;
       char mysteryWord[MAX_LENGTH];

       printf("Welcome to Hangman!\n");

       printf("\n\nChoose an option\n"
                "1) Easy\n"
                "2) Moderate\n"
                "3) Hard\n"

                "Your choice: ");

       scanf("%i", &choice);              a biref menu case
       switch (choice) {
       case 1:
           count = 5;
            break;
       case 2:
           count = 2;
           break;
        case 3:
           count = 1;

       }

       srand(time(NULL));
       index = rand() % WORD_COUNT;

       strcpy(mysteryWord, words[index]);/*actual comparing */
        for (i = 0; i < strlen(mysteryWord); i = i + 1)

       {
           answer[i] = '-';
       }

        answer[i] = '\0';

        printf("%s \n", answer);

        while (1 > 0) {
            printf("\n %i guess(es) left\n", count);
            printf("Guess a letter:");
            scanf("%c\n", &guess);
            guess = tolower(guess);

            found = 0;

            for (i = 0; i < strlen(mysteryWord); i++) 
            {
                if (mysteryWord[i] == guess) {
                    answer[i] = guess;
                    found = 1;
                }
            }
            if (found == 0) {
                printf("Not found!\n");
                --count;
            } 

            if (count == 0) {
                printf("Game over\n");
                printf("The answer is %s.", mysteryWord);
                break;
            }

            else {
                what should be here instead of if(answer==mysteryWord) ?
                if (strcmp(answer, mysteryWord) == 0) 
                {
                    printf("Yes, it's a %s\n", answer);
                    break; /* or return */
                } else
                    printf("%s", answer);   
            }
        }  end of while loop ?

    }  end of main ?

2 个答案:

答案 0 :(得分:1)

更改

  scanf("%c\n", &guess);

  scanf(" %c", &guess);

请注意%c之前的空格。空格会丢弃所有空格,如换行符和空格,%c将扫描下一个非空白字符。

在您的情况下,当您输入任何scanf的数据时,输入数据并按回车键。scanf读取输入的数据并保留\n(换行符)在stdin。当您使用%c扫描字符时,scanf会读取前一个\n遗漏的scanf,因此不会等待输入。

答案 1 :(得分:1)

scanf(" %c", &guess);

请确保您的scanf()%c

之前的空格一样

空间的目的是狼吞虎咽的空白和特殊字符