第一:写一个文件流,读取你保存到电脑上的txt文件到内存中,并且存入一个数组中。
第二:get你猜的单词,然后与之比较。正确返回true错误返回false。判断返回值,true提示通过
false继续。
如果还要复杂点的话,可以在比较判断函数里面添加一些人性化的内容,比如说有几个不相同这类的,凭自己的想想能立来做
分类: 电脑/网络 >>操作系统/系统故障问题描述:
请写一个小游戏程序,程序开始时从文件读入一批单词,文件的名字由命令行得到。程序运行中每次从这些单词中随机地选出一个,要求游戏者猜。做游戏者反复询问某些字母是否出现在单词里,程序给出回答。直至人猜出这个单词(或者放弃)。
解析:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define max 1024
#define min 50
void main()
{
FILE *fp
char c
int i=0
int j=0
读文件
char str[max][min]={0}
if((fp=fopen("word.txt","r"))==NULL)
{
printf("can not open file word.txt\n")
exit(0)
}
c=fgetc(fp)
while(c!=EOF)
{
if(c!=' ')
{
str[i][j]=c
j++
}
else
{
i++
j=0
}
c=fgetc(fp)
}
产生随机数,0-i
srand((unsigned int)time(NULL))
int n=rand()/20
while((n<0)||(n>i))
{
n=rand()/20
}
printf("取得的随机数是第%d个单词\n",n)
检查单词
printf("#######guess begin######\n")
printf("\n")
char gs
char con='y'
while(con=='y')
{
printf("请输入字母,# 号表示结束\n")
scanf("%c",&gs)
getchar()
char gue[min]={0}
int flag=0
while(gs!='#')
{
for(int i=0str[n][i]!='\0'i++)
{
if(str[n][i]==gs)
{
printf("字母%c在单词中\n",gs)
flag=1
break
}
}
if(!flag)
{
printf("字母%不在单词中\n",gs)
}
printf("请输入字母,# 号表示结束\n")
scanf("%c",&gs)
getchar()
}
printf("请输入你猜的单词\n")
scanf("%s",gue)
getchar()
if(!(strcmp(str[n],gue)))
{
printf("恭喜你,猜对了!\n")
}
else
{
printf("很遗憾,你猜错了\n")
}
printf("continue?y is guess again,press any key to end \n")
scanf("%c",&con)
getchar()
}
fclose(fp)
}
修改后如下
你所说的多循环一次是因为输入的回车被读入
目前加了判断略去输入的回车 如果需要略去其他字符 比如空格等 可类似判断
#include<stdio.h>#include<string.h>
main()
{
char *p
int i,count=8,rightcount=0
char answer[]="junk"
char guess,userguess[strlen(answer)]
for (i=0i<strlen(answer)i++)
userguess[i]='-'
userguess[i] = 0//这里 加个结束符
while(rightcount!=strlen(answer)&&count!=0)//这里条件微调了一下
{
printf("The word now looks like this :%s\n",userguess)
if(count!=1)
printf("You have %d guesses left.\n",count)
else
printf("You have only one guess left.\n")
printf("Your guess:")
while(scanf("%c",&guess) && guess == '\n')//略去换行符输入
if((p=strchr(answer,guess)))
{
*(userguess+(p-answer))=*p
rightcount++
*p='-'
printf("The guess is correct.\n")
}
else
{
count--
printf("There are no %c's in the word.\n\a",guess)
}
}
if(rightcount==strlen(answer)) printf("You win.\n")
else printf("You lose.\n")
}