gpt4 book ai didi

c - fgets() strtok()

转载 作者:行者123 更新时间:2023-11-30 19:49:16 25 4
gpt4 key购买 nike

嘿,我的任务是从由空格分隔的文件中读取数据并对数据进行排序。我不断遇到段错误,但我无法弄清楚我的代码出了什么问题。感谢您的帮助。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_LINE 100
#define MAX_NAME 30
int countLinesInFile(FILE* fptr);
int findPlayerByName(char **names, char* target, int size);
int findMVP(int* goals, int* assists, int size);
void printPlayers(int* goals, int* assists, char** names, int size);
void allocateMemory(int **goals, int** assists, char*** names, int size);
void sortPlayersByGoals(int* goals, int* assists, char** names, int size);
void writeToFile(FILE *fptr, int* goals, int* assists, char** names, int size);
void readLinesFromFile(FILE* fptr, int* goals, int* assists, char** names, int numLines);

int main(int argc, char **argv)
{
FILE *fptr;
int size;
int* goals;
int* assists;
char** names;
if(argc != 2)
{
printf("Invalid number of arguments\n");
return 1;
}
fptr = fopen(argv[1], "r");
if(fptr == NULL)
{
printf("Failed to open input file.\n");
return 2;
}
size = countLinesInFile(fptr);
allocateMemory(&goals, &assists, &names, size);
int numLines;
numLines = size;
readLinesFromFile(fptr, goals, assists, names, numLines);
printPlayers(goals, assists, names, size);

return 3;
}
void printPlayers(int* goals, int* assists, char** names, int size)
{
int i;
for(i = 0; i < size; i++)
{
printf("%c %d %d", *(names + i), *(goals + i), *(assists + i));
}

}
void readLinesFromFile(FILE* fptr, int* goals, int* assists, char** names, int numLines)
{
char line[MAX_LINE];
int i;
char* value;

for(i = 0; i < numLines; i++)
{
fgets(line, MAX_LINE, fptr);
value = strtok(line, " ");
*(*names + i) = atoi(value);
value = strtok(line, " ");
*(goals + i) = atoi(value);
value = strtok(line, " ");
*(assists + i) = atoi(value);
}


}
void allocateMemory(int **goals, int** assists, char*** names, int size)
{

*goals = malloc(sizeof(int)* size);
*assists = malloc(sizeof(int)* size);
*names = malloc(sizeof(char*)* MAX_NAME);

}
int countLinesInFile(FILE* fptr)
{
int i;
char line[MAX_LINE];
i = 0;
while(fgets(line, MAX_LINE, fptr) != NULL)
{
i++;
}
rewind(fptr);
return i;
}

--插入--

输入文件如下所示:雷登 2 0伯格伦德 5 2 jack 曼 2 0斯图尔特 4 0押江 3 5麦当劳 2 4皮特兰杰洛 2 7佩隆 2 6塔拉森科 5 5

最佳答案

在 allocateMemory() 中,每个 *names 都是一个 char **。您需要分配两次

*names = malloc(...);
for (<each pointer in names>) {
<pointer> = malloc(...);
}

别忘了释放两次

for (<each pointer in names>) {
free(<pointer>);
}
free(*names);

关于c - fgets() strtok(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990434/

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