【问题标题】:Attempting where to place my error statement within my case statement尝试在我的案例陈述中放置我的错误陈述
【发布时间】: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


【解决方案1】:

IMO,这里最直接的方法是在 for 循环中使用标志。在 cmets 中推荐了一个哈希表,我认为,或者任何其他“更好”的数据结构,都是多余的,因为你必须自己实现它(如果使用 C++,当然,使用std::map)。虽然效率肯定更高,但即使是像足球这样拥有庞大阵容的球队也只有 50-60 名球员。除非您需要极高的速度,否则 for 循环就足够了。处理成千上万条不同的记录会改变我的想法。

#include <stdbool.h>

...

case 'r':
    bool playerFound = false;
    printf("Enter a jersey number:\n");
    int replace;
    // you should check the return value of all your scanf calls, but
    // omitting that here for clarity
    scanf("%d", &replace);  // as mentioned in the comments, this should be replace
    for (int i = 0; i < numPlayers; ++i) {
        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]);
            playerFound = true;
            break; // jersey numbers are unique for each player,
                   // so this is the one and only match, we're done searching
        }
    }
    // check if the player was found here after the loop
    if (playerFound == false)
    {
      // print your error message here
      puts("Player not in roster.");
    }
    break;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2010-10-30
    • 2016-05-13
    • 2016-02-21
    • 1970-01-01
    • 2015-01-24
    • 2020-03-28
    相关资源
    最近更新 更多