#include<stdio.h>
#include<string.h>
#include<time.h>
#include<stdlib.h>
typedef struct dic {
int index;
char string[10];
struct dic *next;
}node;
main() {
FILE *fp;int indexrand;node *head;node *mainhead;
char s[10],question[10],answer[10];char check;
int count=-1,i,j,k,len,flag;head=(node *) malloc(sizeof(node));
mainhead=head;
fp=fopen("dictionary.txt","r");
while((fgets(s,10,fp))!=NULL) {
strcpy(head->string,s);
count++;
(head->index)=count;
head->next=(node *)malloc(sizeof(node));
head=head->next;
}
fclose(fp);
head->next=NULL;
srand(time(NULL));
indexrand=rand()%(count+1);
printf("%d\n",indexrand);
for(head=mainhead;(head->next)!=NULL;head=head->next)
if((head->index)==indexrand)
strcpy(question,(head->string));
printf("%s\n",question);
len=strlen(question);
printf("%d\n",len);
for(i=0;i<len-1;i++)
answer[i]='_';
answer[i]='\0';
printf("%s\n",answer);
printf("6 chances to go\n");
for(i=0,k=6;k>0;i++) {
flag=0;
printf("%d\n",i);
scanf("%c",&check);
for(j=0;j<(len-1);j++) {
if(question[j]==check) {
flag++;
answer[j]=check;
}
}
if(flag>0)
printf("%d chances to go\n",k);
if(flag==0) {
k--;
printf("no common letters...%d chances to go\n",k);
}
printf("%s\n",answer);
}
}
文件 dictionary.txt 每行只有一个单词。
在运行代码时,对于用户的每次尝试(即用户输入字符后),no common letters...%d chances to go\n",k
即使flag > 0
满足条件,也会显示语句。
我该如何纠正?