用户输入整数无限循环直到用户输入一个字符(C)

User Input of Integers Infinite Loop Until User Inputs a Character (C)

我是 C 的新手 - 我打算制作一个程序来显示用户输入 intodd 还是 even,直到用户决定退出输入 char 'x'。循环类型通过检测奇数并用 'x' 终止程序来工作,但是偶数会出现故障 - 为什么会这样?如果您能指出代码中的缺陷,将不胜感激。谢谢

#include <stdio.h>

int main(void)

{
int i=0;
char x = "x";

printf("Enter an integer to check whether your number is odd or even\n");
printf("Enter an ´x´ at any time to quit the program\n");

do
{ 
    scanf("%d", &i);
    
        if (i % 2 == 0) 
        {
            printf("The number is even\n");
        }
        else if (i % 2 != 0)
        {
            printf("The number is odd\n");
        }   
        else("%c ", &x);
        {
            scanf(" %c", &x);
            getchar();
            printf("The program will now terminate\n");
            return 0;
        }
}
    while (i > 0);
        i++;

    return 0;
}   

非常接近,但我标记了一些更改:

#include <stdio.h>

int main(void)

{
int i=0;
char x = 'x';  // Note: single quotes for char, double for string

printf("Enter an integer to check whether your number is odd or even\n");
printf("Enter an ´x´ at any time to quit the program\n");

do
{ 
    int n = scanf("%d", &i);  // Check if number was read
    if (n == 1) {
        if (i % 2 == 0) 
        {
            printf("The number is even\n");
        }
        else  // Only other possibility
        {
            printf("The number is odd\n");
        }

    } else   // No number, see if there's an 'x'
    {
            scanf(" %c", &x);
            if (x == 'x') 
            {
                 printf("The program will now terminate\n");
                 return 0;
            } else
            {
                 printf("Unknown input %c\n", x);
            }
    }
}
    while (i > 0);  // Will also end if user enters <= 0

    return 0;
}