如何使带字符的开关盒工作?

时间:2018-11-11 22:35:54

标签: c arrays switch-statement

我目前正在为我的课程做作业。在C语言中,我必须制作一个与足球队花名册搭配使用的程序,在该程序中可以更新,替换,比较球员等。但是,现在我无法使菜单中的任何选项起作用。使用我的代码可能会更好地理解这一点:

#include <stdio.h>

int main(void) {

    int i, jersey, rating, newJersey, newRating, playerJerseyNumber[5], playerRating[5];
    char choice;

    for (i = 0; i < 5; i++)
    {
        printf("Enter player %d's jersey number: \n", (i + 1));
        scanf("%d", &playerJerseyNumber[i]);
        printf("Enter player %d's rating: \n\n", (i + 1));
        scanf("%d", &playerRating[i]);
    }

    printf("ROSTER\n");
    for (i = 0; i < 5; i++)
    {
        printf("Player %d -- Jersey number: %d, Rating: %d\n", (i + 1), playerJerseyNumber[i], playerRating[i]);
    }

    printf("\n\nMENU \nu - Update player rating \na - Output players above a rating \nr - Replace player \no - Output roster \nq - Quit\n\n");
    printf("Choose an option: \n");
    scanf("%c", &choice);

    switch (choice) {
    case 'u':
    {
        printf("Enter a jersey number: \n");
        scanf("%d", &jersey);
        printf("Enter a new rating for player: \n");
        scanf("%d", &newRating);
        for (i = 0; i < 5; i++)
        {
            if (jersey == playerJerseyNumber[i])
            {
                playerRating[i] = newRating;
            }
        }
        break;
    }

    case 'a':
    {
        printf("Enter a rating: \n");
        scanf("%d", &rating);
        printf("\n ABOVE %d\n", rating);
        for (i = 0; i < 5; i++)
        {
            if (playerRating[i] > rating)
            {
                printf("Player %d -- Jersey number: %d, Rating: %d\n", (i + 1), playerJerseyNumber[i], playerRating[i]);
            }
        }
        break;
    }

    case 'r':
    {
        printf("Enter a jersey number: \n");
        scanf("%d", &jersey);
        printf("Enter a new jersey number: \n");
        scanf("%d", &newJersey);
        printf("Enter a rating for the new player: \n");
        scanf("%d", &newRating);
        for (i = 0; i < 5; i++)
        {
            if (jersey == playerJerseyNumber[i])
            {
                playerJerseyNumber[i] = newJersey;
                playerRating[i] = newRating;
            }
        }
        break;
    }

    case 'o':
    {
        printf("ROSTER\n");
        for (i = 0; i < 5; i++)
        {
            printf("Player %d -- Jersey number: %d, Rating: %d\n", (i + 1), playerJerseyNumber[i], playerRating[i]);
        }
        break;
    }

    default:
        printf("didnt work");
        break;
    }

    return 0;
}

现在,我的代码的第一部分可以正常工作。但是,如果我尝试使用菜单中的任何选项,它们将不起作用。它会自动转为默认大小写并显示“无效”。

现在,我正在

进行测试
84 7
23 4
4 5
30 2
66 9
u
4
6
o
q

即使将4号球衣的等级更新为6,这也不起作用。

关于为什么此方法无效的任何想法?谢谢。

1 个答案:

答案 0 :(得分:2)

use scanf(" %c", &choice) 

格式字符串中的空白告诉scanf跳过前导空白,并且第一个非空白字符将由%c转换说明符读取。

引用Here