为什么我的while循环会产生两个输出实例?

时间:2019-06-16 21:22:38

标签: c while-loop

我正在尝试实现一个while循环,该循环中的函数调用可以迭代5次;而(n <= 5)。但是,当我执行代码时,输​​出会生成while循环的两个实例,或者看起来如此。

int n = 0;
while (n < 5)
{
    PlayLetterGame(); //Function Call
    n = n + 1;
}

//end program
system("pause");
return 0;

PlayLetterGame()

    int ch, ch1;
    int ct = 20;
    srand(time(NULL)); //set RNG

    FILE * fp1;
    char ui0, ui1;
    printf("Please enter your guess\n"); //Prompt User
    scanf("%c", &ui0); // reads the guessed letter and store it in variable
    printf("%s%c\n", "You guessed ", ui0);
    ui1 = toupper(ui0); //toupper function
    printf("%s%c\n", "Toupper Form ", ui1); // Toupper Form Text
    fp1 = fopen("input.txt", "r"); //Open File again

    if (fp1 == NULL)
    {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }
    //check
    int cx = rand();
    //printf("%d\n", cx); // Toupper Form Text
    int cc = cx % ct + 1; //Random number generator
    //printf("%d\n", cc); // Toupper Form Text
    int i = 0;
    while ((ch = fgetc(fp1)) != EOF)
    {
        char ch1;
        ch1 = toupper(ch);
        if ((ch1 >= 65 && ch1 <= 90))
        {
            i++;
            if (cc == i)
            {
                if (ch1 == ui1)
                {
                    printf("%s\n", "Congratulations you picked the right letter");
                    printf("%s%c\n", "The Randomly selected letter was ", ch);
                }
                else
                {
                    if ((ui1 - 3) == ch1 || (ui1 + 3) == ch1 || (ui1 - 2) == ch1 || (ui1 + 2) == ch1 || (ui1 - 1) == ch1 || (ui1 + 1) == ch1)
                    {
                        printf("%s%c\n", "Randomly selected from Text.file ", ch);
                        printf("%s%c\n", "Touppered Form of randomly selected ", ch1);
                        printf("%s%d%s\n", "Ooh so close! You almost had it as you were ", abs(ui1 - ch1), " off");

                    }
                    else
                    {
                        printf("%s%c\n", "Randomly selected from Text.file ", ch);
                        printf("%s%c\n", "Touppered Form of randomly selected ", ch1);
                        printf("%s%d%s\n", "You were ", abs(ui1 - ch1), " off");
                        printf("%s\n", "I am sorry, that is not the right letter!");
                    }
                }
            }
        }
    }

    fclose(fp1);

我希望代码产生提示,要求用户输入他们的“猜测”,然后产生响应。该代码可以执行此操作,但是附加了相同的文本提示,但是该代码并未在此部分要求其他“猜测”。

0 个答案:

没有答案