如何在C中打印switch case中的default语句?

xqkwcwgp  于 2023-10-16  发布在  其他
关注(0)|答案(2)|浏览(123)
#include <stdio.h>

int main()
{
    int a, b, c;

    /* Input two numbers from user */
    printf("Enter two numbers to find maximum: ");
    scanf("%d%d", &a, &b);
    c = a > b;
    switch (c)
    {   
      case 0:
        printf("%d is maximum", b);
        break;

      case 1:
        printf("%d is maximum", a);
        break;

      default:
        printf("Invalid Input");
    }

    return 0;
}

我想在这个C程序中打印默认语句,输入错误的输入,如浮点数或字符常量。每当我输入任何char类型的变量或浮点数时,都会发生这种情况👇
输出示例1:

Enter two numbers to find maximum: 2.5
509 is maximum

输出示例2:

Enter two numbers to find maximum: g
512 is maximum

预期输出应为:

Enter two numbers to find maximum: g
Invalid Input

预期输出应为:

Enter two numbers to find maximum: 22.6
Invalid Input
gcxthw6b

gcxthw6b1#

验证输入和计算表达式应分两个独立的阶段完成:

#include <stdio.h>

int main(void)
{
    char buf[80];
    char eol;
    int a, b;

    /* Input two numbers from user */
    printf("Enter two numbers to find maximum: ");
    if (!fgets(buf, sizeof buf, stdin)) {
        printf("no input\n");
        return 1;
    }
    /* input should be 2 integers and some white space */
    if (sscanf(buf, "%d%d %c", &a, &b, &eol) != 2) {
        printf("invalid input: %s\n", buf);
        return 1;
    }
    if (a > b) {
        printf("%d is maximum\n", a);
    } else {
        printf("%d is maximum\n", b);
    }
    return 0;
}

如果你坚持将状态存储在变量c中,你可以这样做:

#include <stdio.h>

int main(void)
{
    char buf[80];
    char eol;
    int a = 0, b = 0, c = -1;

    /* Input two numbers from user */
    printf("Enter two numbers to find maximum: ");
    if (fgets(buf, sizeof buf, stdin)) {
        /* input should be 2 integers and some white space */
        if (sscanf(buf, "%d%d %c", &a, &b, &eol) == 2) {
            c = a > b;
        }
    }
    switch (c) {
    case 0:
        printf("%d is maximum\n", b);
        break;
    case 1:
        printf("%d is maximum\n", a);
        break;
    default:
        printf("invalid input\n");
        break;
    }
    return 0;
}
q5iwbnjs

q5iwbnjs2#

c = a > b;在理论上只能是1或0。
你真正想要的可能是这个:

c = scanf("%d%d", &a, &b);

switch(c)
{
  case 2: 
    /* expected */
    /* additional error handling of inputs here if needed */
    break;

  default:
    /* scanf failed */
}

相关问题