I am try to write a case statement in C. Currently it fully works except I'm unsure of where to place my error statement. If the select jersey is not within the saved array it needs to output that to the user with a printf such as "Player not in roster".
When I attempt to place it before my for loop it recognized that the element isn't in the array but does not output the error statement. If I place the error inside, it will loop through for how ever many players are there and say that "Player not in roster". Currently, below, is my working case that removes and adds a new player on the roster.
EDIT: The code below is the revision based on the comments and I've added in the error statement. Hopefully it looks better. I have tested it and it is fully functional. Still seeing though that the error statement will reiterate for how every many there are in the jerseyNumber array.
//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");
}
}
IMO, the most straight-forward approach here is using a flag with your for loop. A hash table has been recommended in the comments, I think that, or any other "better" data structure, is overkill, since you'd have to implement it yourself (if using C++, sure, use std::map). While certainly more efficient, even a team with a large roster like football will only have 50-60 players on it. Unless you need extreme speed, a for loop will suffice. Dealing with thousands of different records would change my mind.
#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;