嘿,我的任務是從一個空格分隔的文件讀取數據並對數據進行排序。我一直在收到seg錯誤,我無法弄清楚我的代碼有什麼問題。謝謝您的幫助。fgets()strtok()
#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;
}
- INSERT -
輸入文件看起來像: 雷登2 0 伯格倫德5 2 傑克曼2 0 斯圖爾特4 0 Oshie 3 5 麥當勞2 4 Pietrangelo 2 7 門階2 6 塔拉先科5 5
把printf放在你的代碼中給我們一個關於它在哪裏爆炸的基本概念。或者張貼輸入以及我們可以自己測試:) – alvonellos 2013-02-20 21:40:32
哇! A [三星級程序員](http://c2.com/cgi/wiki?ThreeStarProgrammer):) – pmg 2013-02-20 21:41:35
輸入文件是: 雷登2 0 伯格倫德5 2 傑克曼2 0 斯圖爾特4 0 Oshie 3 5 麥當勞2 4 Pietrangelo 2 7 Perron 2 6 Tarasenko 5 5 – user2093120 2013-02-20 21:44:35