我的输出中得到_ \ 377

时间:2016-12-13 05:26:49

标签: c output

我有一个学校作业来制作一个刽子手游戏。除了一个小故障之外,游戏的工作原理我想要它。如果用户输入的单词是4个字母或更少,则隐藏的单词将在末尾显示一个额外的“_ \ 377”。当用户输入的单词是5个字母或更多时,则没有任何故障。我希望有人能够帮助我解决问题。提前谢谢!

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


int letterfinder(char string[], char a, int vari)
{
int length = strlen(string);
int i = vari;
int val = 0;
while( i <= length && val != 1)
{
    if( string[i] == a)
    {
        val = 1;
    }
    i++;
}
if( val == 0)
{
    return 100;
}
else
{
    return i;
}
}



int main()
{
char inWord[] = "1111111111111111111111111111";
char outWord2[] = "1111111111111111111111111111";
char guess;
int gameover = 0;
int trys = 10;
int vari = 0;
printf("Please enter a word: ");
gets(inWord);
printf("%s\n", inWord);
printf("                            \n");
printf("                            \n");
printf("                            \n");
printf("                            \n");
printf("                            \n");
printf("                            \n");
int i2 = 0;
int j2 = 0;
int i3 = 0;
i2 = strcspn(inWord, outWord2);
char outWord[80];
while(i3 < i2)
{
   outWord[i3] = '1';
    i3++;

}

while(j2 < i2)
{
    outWord[j2] = '-';
    j2++;
}
puts(outWord);

while(gameover != 1 )
{
    printf("What is your guess: ");
    scanf("%s", &guess);
    vari = 0;
    if(letterfinder(inWord, guess, vari) == 100)
    {
        printf("Wrong!");
        trys--;
        printf("You have %d attempts left\n", trys);
        if(trys == 0)
        {
            gameover = 1;
            printf("You ran out of attempts. Game over\n");
        }
    }
    else
    {
        outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
        vari = (letterfinder(inWord, guess, vari));
        while(letterfinder(inWord, guess, vari) != 100)
        {
            outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
            vari = letterfinder(inWord, guess, vari);
        }
        puts(outWord);

    }
    int value = 0;
    i3 = 0;
    while( i3 <= i2)
       {
           if( outWord[i3] == '-')
           {
               value = 1;
           }
           i3++;
       }
    if(value != 1)
    {
        printf("Congratulations, you have guessed the word!\n");
        gameover = 1;
    }

 }
  return 0;
}

1 个答案:

答案 0 :(得分:0)

您的代码具有未定义的行为。在这种情况下,它“起作用”只是偶然/运气。 char guess; scanf("%s", &guess);在将字符串写入只能包含单个字符的变量时会导致内存损坏。由于所有C字符串均以NUL终止,因此即使是单个字母的猜测也需要两个字符来存储。                     –钾盐