我在使用相当基本的代码时遇到了麻烦。我需要从下面显示的文件中读取每一行,用 strtok 将其分成 3 个部分,并将每个部分存储到一个数组中。“goals”和“assists”的数组工作正常,但由于某种原因,整个 name 数组都填充了从文件中读取的姓氏。
输入文件:
Redden 2 0
Berglund 5 2
Jackman 2 0
Stewart 4 0
Oshie 3 5
McDonald 2 4
Pietrangelo 2 7
Perron 2 6
Tarasenko 5 5
相关代码:
int main(int argc, char* argv){
FILE* inFile = fopen(argv[1],"r");
char ** nameArray;
int * goalArray;
int * assistArray;
int size = countLinesInFile(inFile);
allocateMemory(&goalArray, &assistArray, &nameArray, size);
readLinesFromFile(inFile, goalArray, assistArray, nameArray, size);
}
void allocateMemory(int** goals, int** assists, char*** names, int size)
{
*goals = malloc(size*sizeof(int));
*assists = malloc(size*sizeof(int));
*names = malloc(size*sizeof(char *));
int i;
for(i=0; i<size; i++)
{
*(*names + i) = calloc(MAX_NAME,sizeof(char));
}
}
void readLinesFromFile(FILE* fPtr, int* goals, int* assists, char** names, int numLines)
{
int i;
char * buffer = malloc(MAX_LINE*sizeof(char));
for(i = 0; i<numLines; i++)
{
if(fgets(buffer, MAX_LINE, fPtr)!= NULL)
{
names[i] = strtok(buffer, " \n");
goals[i] = atoi(strtok(NULL, " \n"));
assists[i] = atoi(strtok(NULL, " \n"));
}
}
}
出于某种原因,nameArray[0-9] 都包含“Tarasenko”,对此的任何帮助将不胜感激。