简化(和不完整)版本的刽子手游戏中的错误

时间:2014-01-20 17:59:49

标签: c

我写了第一个版本的刽子手。游戏将在稍后完成,此部分代码将起作用。

代码:

#include <stdio.h>
#include <conio.h>



int main()
{
    char word[]={"name"};
    char word0[]={"----"};
    char lett;
    int i;
    int c;
    int e=0;

    while(e<12)
    {
        gotoxy(2,2);
        printf("\n%s\n",word0);
        scanf("%c",&lett);
        for(i=0,c=0;i<4;i++)
        {
            if(lett==word[i])
            {
                word0[i]=word[i];
                c++;
            }
        }


        printf("%d",c);  
        if(c==0)
        {
            e++;
            printf("%d",e);
        }       
    }    
    printf("You lose");
    getchar();
}

程序在我发出12个错误之前结束,每个周期打印两个值(不是1,它应该做),这与实际的错误数不一致。为什么呢?

3 个答案:

答案 0 :(得分:0)

第二个'周期',正如你所说,正在读取换行符。尝试将scanf更改为:

scanf("%c\n",&lett);

答案 1 :(得分:0)

当你按下时,你得到的第二个条目是新行,说“a”,然后是“回车”。 “输入”是一个新的字符,然后由您的程序处理。

不使用scanf("%c",&lett);,而是使用scanf(" %c",&lett);(在'%'=&gt;前面有空格,这会忽略任何空格,新行等。

答案 2 :(得分:0)

一些细微的更改使代码工作。 请注意,我必须稍微更改I / O(没有gotoxy()函数,并且因为我在codepad.org上运行它而没有交互式输入)。查看代码逻辑的不同之处,您应该有解决方案。

我添加了中间printf语句,因此您可以更清楚地跟踪流程 - 通常在调试时是个好主意。

注意 - 您可能希望使用不区分大小写的字符串比较...

#include <stdio.h>
#include <string.h>

int main()
{
    char word[]="name";
    char word0[]="----";
    char guess[]="bnexacdfm";
    char lett;
    int i;
    int c;
    int e=0;
    int gi = 0;

    while(e<12 && gi < strlen(guess))
    {
//        gotoxy(2,2);
        printf("\n%s\n",word0);
        lett = guess[gi++];
        printf("you guessed: %c\n", lett);
// scanf("%c",&lett);
        for(i=0,c=0;i<4;i++)
        {
            if(lett==word[i]) // really want case insensitive comparison here
            {
                word0[i]=word[i];
                printf("found %c at position %d\n", lett, i);
                c++;
            }
        }


        printf("Number correct in this guess: %d\n",c);  
        if(c==0)
        {
            e++;
            printf("Total number of incorrect guesses: %d\n",e);
        }       
    }    
    if(strcmp(word, word0)==0) {
      printf("well done! you win\n");
    }
    else {
      printf("Sorry - you lose\n");
    }
    return 0;
//    getchar();
}

输出:

----
you guessed: b
Number correct in this guess: 0
Total number of incorrect guesses: 1

----
you guessed: n
found n at position 0
Number correct in this guess: 1

n---
you guessed: e
found e at position 3
Number correct in this guess: 1

n--e
you guessed: x
Number correct in this guess: 0
Total number of incorrect guesses: 2

n--e
you guessed: a
found a at position 1
Number correct in this guess: 1

na-e
you guessed: c
Number correct in this guess: 0
Total number of incorrect guesses: 3

na-e
you guessed: d
Number correct in this guess: 0
Total number of incorrect guesses: 4

na-e
you guessed: f
Number correct in this guess: 0
Total number of incorrect guesses: 5

na-e
you guessed: m
found m at position 2
Number correct in this guess: 1
well done! you win

链接到代码示例:http://codepad.org/56dC0stD