字符串打印额外值C编程

时间:2015-03-10 20:46:37

标签: c string string.h

我目前正在上课,但在打印和检查字符串时遇到一些问题。基本上它是挂人,我需要打印单词只是_(下划线),每个下划线分隔空格。我只是填写一个框架代码,我必须填写的代码如下:

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;
}

1 个答案:

答案 0 :(得分:1)

最终'\0'的排名在initializeBlankString

中计算错误
revealedLetters[numLetter - 1] = '\0';

应该是:

revealedLetters[numLetter] = '\0';

您的代码还有很多问题:

  • Modern C强制执行函数返回类型。前2个void,后2个int

  • 您无法将字符数组与if(word == revealedLetters)

  • 进行比较