我的do while正在终止,而不是继续我的C程序



当我试图在不调试代码的情况下运行时,一切都很顺利,但只要我按下Y,就可以继续输入数字,它就会终止(必须说我需要帮助(

int main() {
    int a;
    char c;
    do {
        puts("dwse mou enan arithmo: ");
        scanf_s("%d", &a);
        if (a > 0) {
            if (a % 2 == 0)
                printf("the number %d is even n", a);
            else
                printf("the number %d is odd n", a);
        } else {
            printf("the program won't run with negative numbers n");
        }
        printf("if you want to proceed press y or Y :");
        c = getchar();
        getchar();
    } while (c == 'y' || c == 'Y');
    return 0;
}

getchar()读取的字符是挂起的换行符,该换行符在数字之后键入,但未被scanf_s使用。

在为继续测试读取下一个字符之前,您应该使用这个挂起的换行符,这可以在scanf中很容易地完成,%c转换规范之前有一个空格:

#include <stdio.h>
int main() {
    int a;
    char c;
    for (;;) {
        printf("dwse mou enan arithmo: ");
        if (scanf_s("%d", &a) != 1)
            break;
        if (a >= 0) {
            if (a % 2 == 0)
                printf("the number %d is evenn", a);
            else
                printf("the number %d is oddn", a);
        } else {
            printf("the program does not accept negative numbersn");
        }
        printf("if you want to proceed press y or Y: ");
        if (scanf_s(" %c", &c) != 1 || (c != 'y' && c != 'Y'))
            break;
    }
    return 0;
}

最新更新