-
I might write it like this:
Code:
static int get_player_name(Hand *player)
{
char line[sizeof(player->player_name) + 1]; // +1 for newline
if (!fgets(line, sizeof(line), stdin))
{
// maybe the user triggered EOF or something, so for our purposes, bail out:
fprintf(stderr, "Error: unexpected end-of-file or read failure\n");
exit(EXIT_FAILURE);
}
char *newline = strchr(line, '\n');
if (!newline)
{
printf("Incorrect Entry: name must have a length of no more than %zu characters\n",
sizeof(player->player_name) - 1);
flush_line();
return 0;
}
if (newline == line)
{
printf("Incorrect Entry: name cannot be blank\n");
return 0;
}
*newline = '\0';
strcpy(player->player_name, line);
return 1;
}
void get_player_names(int num_of_players, Hand players[])
{
for (int i = 0; i < num_of_players; i++)
{
do
{
printf("Please enter player %d's name: ", i + 1);
}
while (!get_player_name(players + i));
}
// this is ok for debugging, otherwise it should not be here:
for (int i = 0; i < num_of_players; i++)
{
printf("Player %d's name is %s\n", i, players[i].player_name);
}
}
-
wow thank you so much you thought of everything and its so much more concise than my effort above
thanks
coop
-
Unfortunately, while restructuring my code I removed a crucial line, and didn't notice the omission because I wasn't testing the code. Basically, the original idea behind the strchr was to remove the newline, but I left that out. So, immediately before the strcpy call, you need to replace the newline character with a null character. I have updated my code accordingly.
-
thanks for the update it all works great. dumb dumb here forgot to add get_player_name to the list of function prototypes but it still ran ok is that because it was being called by a function below it?
coop