首页 > 解决方案 > C程序循环重复两次而不是一次

问题描述

我刚开始编码,很抱歉这个愚蠢的问题。这是C编程。当用户输入Y时,代码按预期运行。如果用户输入N或任何其他字符,程序会循环,但由于某种原因它会重复同一行两次。例如:

Input: Y
Output: The game will now start!
Input: N
Output: Waiting...
Would you like to start the game? <Y/N>:
 is not a valid response
Would you like to start the game? <Y/N>:

如您所见,线路双打,我该如何解决这个问题?

do {
    printf("Would you like to start the game? <Y/N>: ");
    scanf("%c", &cGameStart);
    if (cGameStart == 'Y')
        printf("\nThe game will now start!\n");
    if (cGameStart == 'N')
        printf("\nWaiting...\n\n");
    if ((cGameStart != 'Y') && (cGameStart != 'N'))
        printf("%c is not a valid response\n", cGameStart);
} while (!(cGameStart == 'Y'));

标签: cloops

解决方案


该评论与问题无关。

问题是\n缓冲区中留下的字符scanf。吃它,它会按预期工作。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char cGameStart;
    do {
        printf("Would you like to start the game? <Y/N>: ");
        scanf("%c", &cGameStart);
        if (cGameStart == 'Y')
            printf("\nThe game will now start!\n");
        if (cGameStart == 'N')
            printf("\nWaiting...\n\n");
        if ((cGameStart != 'Y') && (cGameStart != 'N'))
            printf("%c is not a valid response\n", cGameStart);
        fgetc(stdin);
    } while (!(cGameStart == 'Y'));
    printf("Game started\n");
}

推荐阅读