0

我目前正在课堂上玩游戏,但在打印和检查字符串时遇到了一些问题。本质上它是hang man,我需要将单词打印为_(下划线),并用空格分隔每个下划线。我只是在填写一个骨架代码,我必须填写的代码如下所示:

initializeBlankString(const int numLetter, char revealedLetters[25])
{
  int i;
  for(i=0;i < numLetter; i++){
    revealedLetters[i] = '_';
  }
 revealedLetters[numLetter - 1] = '\0';
}

printWithSpaces(char revealedLetters[25])
{
  int i;
  for(i=0;i<(strlen(revealedLetters));i++){
    printf("%c ", revealedLetters[i]);
  } 
}

revealGuessedLetter(char word[], char revealedLetters[25], char guess)
{
  int i, n = 0;
  for(i=0;i<strlen(word);i++){
    if (word[i] == guess){
      revealedLetters[i] = guess;
      n = 1;
    }
  }
  return n;
}

checkGuess(char word[25], char revealedLetters[25])
{
  if(word == revealedLetters)
    return 1;
  else
    return 0;
}

我尝试了很多不同的事情,但我无法成功。问题是,当这个词类似于 unix 时,它会显示_ _ _ _ + r 6 _,而不是_ _ _ _我想我逃脱了,但它看起来不像。

函数调用如下所示:

initializeBlankString(strlen(word), revealedLetters);
printWithSpaces(revealedLetters);
charRevealed = revealGuessedLetter(word, revealedLetters, guess);
won = checkGuess(word, revealedLetters);

解决方案:

void initializeBlankString(const int numLetter, char revealedLetters[25])
{
  int i;
  for(i=0;i < numLetter; i++){
    revealedLetters[i] = '_';
  }
 revealedLetters[numLetter] = '\0';
}

void printWithSpaces(char revealedLetters[25])
{
  int i;
  for(i=0;i<(strlen(revealedLetters));i++){
    printf("%c ", revealedLetters[i]);
  } 
}

int revealGuessedLetter(char word[], char revealedLetters[25], char guess)
{
  int i, n = 0;
  for(i=0;i<strlen(word);i++){
    if (word[i] == guess){
      revealedLetters[i] = guess;
      n = 1;
    }
  }
  return n;
}

int checkGuess(char word[25], char revealedLetters[25])
{
  for(int i = 0; i < strlen(word);i++){
    if(word[i] != revealedLetters[i])
      return 0;
  }
  return 1;
}
4

1 回答 1

1

决赛的位置'\0'计算错误initializeBlankString

revealedLetters[numLetter - 1] = '\0';

应该:

revealedLetters[numLetter] = '\0';

您的代码还有更多问题:

  • 现代 C 要求函数返回类型。 void前2个,int后2个。

  • 您不能将 char 数组与if(word == revealedLetters)

于 2015-03-10T20:58:56.473 回答