接口
#ifndef_randword_h
#define_randword_h
#include <stdio.h>
void Initdictionary(FILE* words);
char* ChooseRandomWord(void);
#endif
接口实现
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <randword.h>
char *a[10];
void Initdictionary(FILE *words)
{
int i;
for(i=0;i<=9;i++)
fgets(a[i],20,words);
}
char* ChooseRandomWord(void)
{
srand((int)time(NULL));
return a[rand()%10];
}
主程序
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <randword.h>
main()
{
FILE *infile;
char guess[20];
int chance,len,i,flag,lefts;
char letter;
chance=8;
printf("Welcome to number game\n");
infile=fopen("words.txt","r+");
if(infile==NULL)
{
printf("Find no word.\n");
break;
}
Initdictionary(infile);
guess=ChooseRandomWord();
len=strlen(guess);
lefts=len;
printf("The word now looks like this:");
for(i=0;i<len;i++)
printf("_");
printf("\n");
printf("You have 8 guesses left.\n");
while((chance>0)&&(lefts>0))
{
printf("Guess a letter:");
scanf("%c",letter);
flag=0;
for(i=0;i<len;i++)
{
if(a[i]==letter)
{
printf("That guess is correct.\n");
flag=1;
break;
}
}
if(flag==0)
{
printf("There is no %c in the word\n",letter);
chance--;
}
printf("The word now looks like this:");
for(i=0;i<len;i++)
{
if(a[i]==letter)
{
printf("%c",letter);
lefts--;
}
else
printf("_");
}
printf("\n");
printf("You have %d guesses left.\n",chance);
}
if(chance==0)
printf("You lose.\n");
if(lefts==0)
printf("You win.\n");
}