c - C 语言的刽子手控制台游戏

标签 c linked-list

#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 letter...%d opportunity to go\n",k即使满足 flag > 0 条件。

如何纠正这个问题?

最佳答案

线路

 scanf("%c",&check);

正在读取用户输入的字符,包括换行符

您可能只想读取该行的第一个字符:使用 fgets() 读取整行,然后设置 check = line[0]

关于c - C 语言的刽子手控制台游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13074022/

相关文章:

C 转换语法和 typedef

c++ - 获取 Windows 上的分区列表

C++ 在单链表中插入值时出错 (E0137)

C-尝试删除链表中的第一个节点时出现双重释放错误

C 中逐字比较字符串

c - C 中单元测试的自动生成器

c - C 中的变量声明概念

java - 链表删除错误

c - 当向hashmap中的链表添加第一个节点时,为什么必须将新节点直接分配给索引指针?

java - LinkedList 程序无响应;可能的空指针错误