#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int compare(char word[], char mystery[])
{
int i=0;int bool=1;
while((i<=20)&&(bool==1))
{
if (word[i]==mystery[i])
i++;
else
bool=0;
}
return bool;
}
char readCharacter()
{
char character = 0;
character = getchar();
character = toupper(character);
while (getchar() != '\n') ;
return character;
}
void readString(char *word,char *mystery)
{
int i=0;
printf("Enter the word to guess : ");
scanf("%s",word);
while(*((word)+(i)) != '\0')
{
*((word)+(i))= toupper(*(word+i));
*((mystery)+(i))='*';
i++;
}
*(mystery+i)='\0';
}
void process(char *word,char *mystery,char letter,int *change)
{
int i=0;
while (*((word)+(i))!= '\0')
{
if (*((word)+(i))==letter)
{
*((mystery)+(i))=letter;
*change=1;
}
i++;
}
}
void test(char *word,char *mystery, int triesleft)
{
if (*mystery!=*word)
{
printf("The mystery word is : %s",*mystery);
printf("\n You have %d tries left.", triesleft);
}
else
{
printf("You won !");
}
}
int main()
{
int triesleft = 10; int change=0;
char word[20]; char mystery[20];char letter;
readString(&word,&mystery);
while((compare(word,mystery)==0) && (triesleft>0))
{
change=0;
printf("Enter the letter :");
letter=readCharacter();
process(&word,&mystery,letter,&change);
if ((change)==1)
triesleft--;
test(&word,&mystery,triesleft);
}
if (triesleft>0)
return 0;
printf("You lost.");
return 1;
}
我是C初学者,我想用C语言编写一个简单的Hang子手游戏,它编译的很好,但它似乎在输入第一个字母后崩溃,我找不到解决方案! 我不知道可能是什么原因,但我有很多的使用字符串用C麻烦,因为它们不存在,也许那是一个糟糕的操作我不知道:/程序崩溃,无法解释为什么?
你的程序没有“编译好”,出现了大量的警告。确保你打开你的编译器的警告设置并修复它们。另外,开始变小。如果你在第一个函数调用时编写了崩溃,除非你明白问题是什么,否则将其他所有东西都去掉并且简化这个函数(让它做更少的事情)。 – Mat 2014-11-08 07:39:12
请指出它发生崩溃的位置,并显示错误消息 – Eric 2014-11-08 07:39:19
此行有问题。 '而(第(i <= 20)&&(布尔== 1))'。对于包含'20'项的数组,最高有效索引是'19',而不是'20'。 – 2014-11-08 07:41:31