[英]hangman console game in c
#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
條件no common letters...%d chances to go\\n",k
該語句也no common letters...%d chances to go\\n",k
。
我該如何糾正?
線
scanf("%c",&check);
正在讀取用戶鍵入的字符, 包括換行符 。
您可能只想讀取該行的第一個字符:使用fgets()讀取整行,然后設置check = line[0]
。
printf("%d\n",i);
scanf("%c",&check);
由於這些語句,scanf將\\ n作為參數,因此每次都打印“沒有常用字母...”。將上面的代碼替換為
printf("%d",i);
scanf("\n%c",&check);
我認為您想將字符串傳遞給scanf,因此請嘗試:
scanf(“%s”,&check);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.