gpt4 book ai didi

c - 将文件中的随机名称分配给结构名称

转载 作者:行者123 更新时间:2023-11-30 16:43:21 24 4
gpt4 key购买 nike

我目前正在用 C 语言编写一个程序,该程序最终将成为一个赛马游戏。我所坚持的部分是从文件生成随机名称。我正在使用马的结构和存储 10 匹马的链接列表。这些名称位于文件“Names”中。我想在文件中随机选择一行,转到它,将名称复制到链表中的当前节点,然后转到下一匹马。目前,当我启动它时它停止响应并返回 -1073741819 (0xC0000005)

我在使用 C 与文件交互方面不太有经验,因此非常感谢任何帮助。

struct node{
int data;
float mult;
float payout;
int score;
struct node *next;
char name[20];//Where I'm trying to store the random name.
};


void rand_name(node* head, int i){
//A function to generate a random name from a list of 3162 names.

FILE* infile;
infile = fopen("Names","r");

if(infile == NULL){
printf("Error opening Names.txt");
exit(EXIT_FAILURE);
}
int cnt, j = rand() % 3162;//Pick a random line to copy.
char buff[100];

node *tmp = NULL;
tmp = malloc(sizeof(node));
tmp = head;

for(cnt = 0; cnt < 1; cnt++){
tmp = tmp->next; //Get to the current node.
}
cnt = 0;
while(cnt < j){
//Copy each line until you get to the random line to copy.
fgets(buff, 100, infile);
j++;
}

strcpy(tmp->name, buff); //Store the last copied line into the node.

return;
}

最佳答案

使用 struct 关键字以及结构名称。即,在程序中使用 struct node 而不仅仅是 node

考虑将 srand()rand() 一起使用,否则每次运行程序时,rand() 可能会返回相同的值.

当您在使用 fgets() 读入 buff 后执行 strcpy(tmp->name, buff); 时,请记住 fgets() 将保留换行符(\n) 位于字符串末尾。您可能想删除它。

如果您尝试打开名为 Names.txt 的文件,则应编写 fopen("Names.txt","r"); 而不是 fopen("名称","r");

BLUEPIXY指出在

tmp = malloc(sizeof(struct node));
tmp = head;

您首先将内存分配给tmp,然后通过用head覆盖tmp来孤立该内存。使用另一个变量来存储新节点。

我认为您只想为 headname 分配一个值。如果是这样,则无需创建新节点。

Felix Guo指出,当您使用完文件流后,请使用 fclose() 关闭文件流。

编辑:当然,您需要将 while 循环中的 j++ 更改为 cnt++,但您已经注意到了这一点。

关于c - 将文件中的随机名称分配给结构名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45315484/

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