【问题标题】:Hangman in C. Questions regarding arrays and stringsC中的刽子手。关于数组和字符串的问题
【发布时间】:2014-07-04 04:43:33
【问题描述】:

好的,这是我的代码。我应该制作一个程序,向一个玩家询问一个单词并要求另一个玩家找到它,一次猜测一个字母。所以基本上,刽子手。我的问题是:

当我尝试将SCounter 变量增加一时,它会增加到随机数。我已经尝试过思考它,但我不知道为什么。例如,当猜测词为Kala(希腊语为“Good/Fine”)时,当我在第一个字母之后输入guess any letter 时,SCounter 等于错误的字母数量。

我的第二个问题是关于guess。我的程序只有在我写char guess[2] 时才有效。当我写char guess[0] 时,它会永远循环。我不明白为什么。

int main(int argc, char *argv[]) {

SetConsoleOutputCP(1253);

int i = 0;
start :printf("Enter the guess word: ");
char word[25], sword[25];
char guess[2];
char alphabet[28] = {"abcdefghijklmnopqrstuvwxyz "};
int Counter = 6;
int SCounter = 0; 
gets(word);
for (i=0; i<strlen(word); i++){
    sword[i]='-';
}
while(Counter != 0)
{
    printf("So far: ");
    for(i = 0; i < strlen(alphabet); i++)
    {
        printf("%c", alphabet[i]);
    }
    printf("\n");
    printf("Guess a character: ");
    gets(guess);
    printf("\n");
    for(i = 0; i < strlen(word); i++)
    {
            if(word[i] == guess[0])
            {
                sword[i] = guess[0];
            }
            /*else
            {
                Counter--;
                printf("You only have %d wrong guesses left.\n", Counter);
            }*/
    }
    for(i = 0; i < strlen(sword); i++)
    {
        if (word[i]==sword[i]){
            SCounter++;
        }
        printf("%c", sword[i]);
    }
    printf("\n");
    printf("%d letters found so far.", SCounter);
    printf("\n");
    for(i = 0; i < strlen(alphabet); i++)
    {   
        if  (strlen(guess)<2)
        {
        if(alphabet[i] == guess[0])
            {
            alphabet[i] = '-';
            }
        }
    }
    if (SCounter == strlen(word)){
        Counter = 0;
    }
    if (strcmp(word, sword)==0){
        printf("Congratulation Player 1! You win!\n");
        goto start;
    }
}
return 0;

}

【问题讨论】:

  • char guess[0] 声明一个长度为零的字符串。这似乎不是很有用。你说“当我尝试将 SCounter 变量增加一时,它会消失”......“变量消失”实际上是什么意思?
  • 我实际上忘记正确结束措辞哈哈。我会编辑它。

标签: c


【解决方案1】:

看起来SCounter 变量在迭代之间没有重置为零,所以它一直在增长。

SCounter 的声明/初始化移动到用于修复此问题的范围内:

int SCounter = 0; // This is where the declaration should be
// Remove the declaration of SCounter at the outermost scope.
for(i = 0; i < strlen(sword); i++)
{
    if (word[i]==sword[i]){
        SCounter++;
    }
    printf("%c", sword[i]);
}

以下是关于程序其余部分的一些注意事项:

  • 使用goto 不会与您的教练一起获得额外分数。对许多人来说,这是一个危险信号。考虑在没有goto 的情况下重写。
  • gets 函数本质上是不安全的。请不要将其用于新的开发。请改用fgets(guess, 2, stdin);

【讨论】:

  • 哇,我真笨。实际上,我移动了很多声明以使其他一切正常工作,但我完全忘记了那个。该程序现在有效。如果我想在没有goto 的情况下编写它,那么我假设我只是将声明移动到第一个while 循环中。除了计数器一个对吗?
  • 我刚刚注意到,如果密码只有一个字母,程序就无法运行。
  • @user3601507 你需要一个额外的while 循环(实际上我更喜欢do/while,因为你想至少运行一次,这就是@ 987654333@/while 循环最适合。
猜你喜欢
  • 2014-09-10
  • 2021-01-09
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多