gpt4 book ai didi

c - 我的链接列表没有从头打印出来

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:21 32 4
gpt4 key购买 nike

我的程序遇到的问题是我创建了一个链表,但是当我打印出链表时,它只打印出列表中的最后一个人。它应该打印出列表中的每个人。这是我的程序中唯一的问题,如果有人能指出正确的方向,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define MAX_PLAYERS 9
#define MAX_STR_LEN 25

typedef struct Player_ {
char name[MAX_STR_LEN];
int number_of_hits;
int number_of_strikes;
struct Player_ *next;
} Player;

int pitch_result(void);
Player *add_player(Player *first_player, const char *name);
void destroy_team(Player *first_player);
void display_line_up(Player* first);
void readFile(Player **lineup, const char* file);

int main(int argc, char *argv[]) {
if(argc < 2){
exit(1);
}
srand(time(NULL));
int strikes = 0;
int hits = 0;
Player *lineup = NULL;
readFile(&lineup, argv[1]);
printf("\nLine up for this team is: ");
display_line_up(lineup);

printf("\n\n%s is batting \n", lineup->name);

for ( ; strikes < 3; ) {
int result = pitch_result();
if (result) {
++hits;
}
else
++strikes;
}

printf("\nScore of game was: %d\n", hits/4);
return 0;
}

void readFile(Player **lineup, const char* file){
FILE *input;
input = fopen(file, "r");
if(input == NULL){
printf("Failed to open");
}
char player[MAX_STR_LEN];
while(fscanf(input, "%s", &player) != EOF){
// printf("\n%s", player);
*lineup = add_player(*lineup, player);
}
}

int pitch_result(void) {
int result;
result = rand() % 2;
return result;
}

void destroy_team(Player *first_player){
Player *temp = first_player->next;
Player *free_player;

while (temp) {
free_player = temp;
temp = temp->next;
free(free_player->name);
free(free_player);
}
}

Player *add_player(Player *first_player, const char *name) {
Player *new_player = (Player*)malloc(sizeof(Player));

int nameLength;
nameLength = strlen(name);

// new_player->name = malloc(nameLength * sizeof(char));

new_player->next = NULL;

strncpy(new_player->name, name, nameLength);
new_player->number_of_hits = 0;
new_player->number_of_strikes = 0;

return new_player;
}

void display_line_up(Player *first){

if(first == NULL)
printf("\nThe list is empty");
else {
while(first != NULL){
printf("\n%s", first->name);
first = first->next;
}
}
}

这是我运行程序时读入的文件(stats.txt)

Yadier_Molina
Allen_Craig
Daniel_Descalso
Rafael_Furcal
David_Freese
Matt_Holiday
Jon_Jay
Carlos_Beltran
Matt_Adams

这是为我的程序提供的示例输出

Line up for this team is:   

Yadier_Molina
Allen_Craig
Daniel_Descalso
Rafael_Furcal
David_Freese
Matt_Holliday
Jon_Jay
Carlos_Beltran
Matt_Adams
Yadier_Molina is batting
Strike!
hit!
Strike!
Strike!

Score of game was: 0

最佳答案

您的 add_player 函数返回一个指向包含新玩家的节点的指针——并且与先前存在的列表没有任何联系(甚至从未使用过变量 first_player) .

您的 readFile 函数使用它,每次读取新玩家的名字时丢弃旧列表:

*lineup = add_player(*lineup, player);

所以结果列表只包含最后一个玩家。

关于c - 我的链接列表没有从头打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24493279/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com