我的scanf循环之一是在执行之前要求两个输入。空格问题?

时间:2019-04-06 21:33:05

标签: c scanf

语言:C

编译器:Visual Studio 2017 / Win 32

因此,基本上我的任务是制作一个乘法游戏,该游戏需要两个随机的单个数字,并提示用户将它们相乘。该程序必须是防弹的,因此必须循环用户,直到他们输入正确的输入为止(例如,如果输入字母,则必须循环用户直到他们输入正确的NUMBER)。我已经尝试了一些方法,do / while循环似乎运行得很好。但是,当用户输入错误的答案并再次尝试时,2ND do / while循环中的scanf将使他们输入两个输入(忽略第一个输入)。我过去曾遇到过这个问题,并尝试了无数次来解决它,但我找不到解决方案。任何帮助将非常感激。

谢谢!

尝试使用fgets。惨败。我删除了getchar()!='\ n'。那行得通,但随后程序将无限循环“请输入整数”。

    while (answer != correct)
    {
        srand(time(NULL));
        int wrong = 1 + rand() % 5;

        switch (wrong)
        {
        case 1:
            SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
            printf("\n               ***\n");
            printf("              Wrong!\n");
            printf("               ***\n");
            SetConsoleTextAttribute(h, wOldColorAttrs);
            break;
        case 2:
            SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
            printf("\n                ***\n");
            printf("               Nope!\n");
            printf("                ***\n");
            SetConsoleTextAttribute(h, wOldColorAttrs);
            break;
        case 3:
            SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
            printf("\n                 ***\n");
            printf("              Not quite!\n");
            printf("                 ***\n");
            SetConsoleTextAttribute(h, wOldColorAttrs);
            break;
        case 4:
            SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
            printf("\n              ***\n");
            printf("          Incorrect!\n");
            printf("              ***\n");
            SetConsoleTextAttribute(h, wOldColorAttrs);
            break;
        case 5:
            SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
            printf("\n                 ***\n");
            printf("          Nope! Try again!\n");
            printf("                 ***\n");
            SetConsoleTextAttribute(h, wOldColorAttrs);
            break;
        }

        do {
        printf("Enter a number to represent your answer! ");
        while (getchar() != '\n');
        } while (scanf_s("%d", &answer) != 1);
        getchar();
    }

我只希望用户能够顺利输入一个数字,而不会引起混乱的scanf错误。

1 个答案:

答案 0 :(得分:0)

您可以在此示例中获取输入

#include <stdio.h>

int main(void)
{
    char anstr[100];
    int answer;
    do { 
        printf("Enter ... answer! ");
        if(fgets(anstr, sizeof anstr, stdin) == NULL) {
            return 1;
        }
    } while(sscanf_s(anstr, "%d", &answer) != 1);
    printf("The answer is %d\n", answer);
    return 0; 
}

理由是%d格式说明符将占用所有前导空格,并且错误的输入将通过读取另一个字符串输入而转储。

计划会议:

Enter ... answer! alice
Enter ... answer! bob
Enter ... answer! 42
The answer is 42