c中hangman程序的麻烦

时间:2012-03-15 22:03:28

标签: c

在for循环中,在if语句中,由于某种原因,它会遍历两个if语句,即使它们彼此相反,我也不知道它为什么这样做。我尝试过不同的方式,但仍然以同样的方式出现。

#include <stdio.h>
#include <stdlib.h>



int main ()
{
char secretword[20] = {};
char alphabet[28] = {"abcdefghijklmnopqrstuvwxyz "};
char guess[2] = {};
int i = 0, k = 0;
int seclength = 0, alphlength = 0;
int GuessCtr = 6;

printf("You Get six chances to guess all of the letters in a phrase\n");
printf("Enter the secret word/phrase: ");
scanf("%s", &secretword);
seclength = strlen(secretword);
alphlength = strlen(alphabet);
while(GuessCtr != 0)
{
    printf("Past guesses: ");
    for(i = 0; i < alphlength; i++)
    {
        printf("%c", alphabet[i]);
    }
    printf("\n");
    printf("Guess a character: ");
    scanf("%s", &guess);
    printf("\n");
    for(i = 0; i < seclength; i++)
    {
            if(secretword[i] == guess[0])
            {
                secretword[i] = '*';
            }
            /*else
            {
                GuessCtr--;
                printf("You missed - you have %d wrong guesses left!", GuessCtr);
            }*/
            if(secretword[i] != guess[0])
            {
                GuessCtr--;
                printf("You missed - you have %d wrong guesses left!", GuessCtr);
            }
    }

    for(i = 0; i < seclength; i++)
    {
        printf("%c", secretword[i]);
    }
    printf("\n");
    for(i = 0; i < alphlength; i++)
    {
        if(alphabet[i] == guess[0])
        {
            alphabet[i] = '*';
        }
    }
}
printf("You suck!");


return 0;

}

2 个答案:

答案 0 :(得分:2)

因为第一个if语句的主体更改了它测试的变量,第二个将再次测试。当评估第二个if时,变量的值与第一次的值不同。

要解决此问题,您需要使用else,因此从第一次“记住”这个条件:

        if(secretword[i] == guess[0])
        {
            secretword[i] = '*';
        }
        else
        {
            GuessCtr--;
            printf("You missed - you have %d wrong guesses left!", GuessCtr);
        }

答案 1 :(得分:1)

我怀疑你被误导了该计划的错误。

由于这看起来像是作业,我不会回答整体情况,但你应该仔细检查这句话以找出错误:

scanf("%s", &secretword);