【发布时间】:2021-12-14 18:29:35
【问题描述】:
我正在尝试用 C 语言编写 case 语句。目前它完全可以工作,只是我不确定将错误语句放在哪里。如果选择的球衣不在保存的数组中,则需要使用 printf 将其输出给用户,例如“Player not in roster”。
当我尝试将它放在我的 for 循环之前,它识别出该元素不在数组中,但不输出错误语句。如果我将错误放在里面,它将循环显示有多少玩家,并说“玩家不在名单中”。目前,下面是我的工作案例,它在名单上删除并添加了一名新球员。
编辑:下面的代码是基于 cmets 的修订,我已在错误语句中添加。希望它看起来更好。我已经对其进行了测试,并且功能齐全。仍然看到错误声明将重申 jerseyNumber 数组中有多少个。
//case r allows for a player to be replaced
case 'r':
printf("Enter a jersey number:\n");
int replace;
scanf("%d", &replace);
for (int i = 0; i < numPlayers; ++i) {
//if the user input matches a jersey in the array the user will input a new jersey number and rating
if (replace == jerseyNumber[i]) {
printf("Enter a new jersey number:\n");
scanf("%d", &jerseyNumber[i]);
printf("Enter a rating for the player:\n");
scanf("%d", &playerRating[i]);
}
//else the error statement will tell the user that the player is not in the array
else {
printf("Player not in roster\n");
}
}
【问题讨论】:
-
从高层次的角度来看,最好使用地图而不是数组?
-
@Neil:C 不提供地图作为内置或库功能。
-
您使用的是未初始化的
replace。 -
你有 UB(未定义的行为)。
replace已初始化。如果你用-Wall编译,编译器会标记这个。您的第一个scanf在for循环之外,因此i未 定义/声明(即错误)。结果,这甚至不能干净地编译 -
您对
i的使用会令人困惑,因为将其用作循环变量会“遮蔽”i的前一个实例,并且更多地用于相同目的:@ 987654330@.
标签: c for-loop switch-statement