【发布时间】:2013-10-31 01:19:54
【问题描述】:
我有一个函数应该读取文件,将单独的行作为单独的元素放入数组中。然后它应该遍历数组并将某些元素放在结构中的某些位置。
我几乎拥有它...当我去打印结构以确保一切正常时,会出现额外的字符!
这是文件中的内容:
123
pre
45
cse
67
345
ret
45
cse
56
这就是它正在打印的内容:
123
pre
45
cse
C
67
345
ret
45
cse
8
56
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct students //Defining structure for students
{
int id; //Students ID Number
char name[30]; //Students Name
int age; //Students Age
char dept[4]; //Studets Department
int grade; //Students Grade
};
int main()
{
struct students list[20];
FILE *f;
char line[30];
char **temp = NULL;
int num_righ = 0;
int id5;
int age5;
int grade5;
int i, k;
f = fopen("records.txt", "r");
while(fgets(line, sizeof (line), f) != NULL)
{
if (line != NULL)
{
num_righ++;
temp = (char**)realloc(temp, sizeof(char*) *num_righ);
temp[num_righ - 1] = strdup(line);
}
}
fclose(f);
k = 0;
i = 0;
while (temp[i] != NULL)
{
id5 = atoi(temp[i]);
list[k].id = id5;
i++;
strcpy(list[k].name, temp[i]);
i++;
age5 = atoi(temp[i]);
list[k].age = age5;
i++;
strcpy(list[k].dept, temp[i]);
i++;
grade5 = atoi(temp[i]);
list[k].grade = grade5;
i++;
k++;
}
for (i = 0; i < k; i++)
{
printf("%d\n", list[i].id);
printf("%s", list[i].name);
printf("%d\n", list[i].age);
printf("%s\n", list[i].dept);
printf("%d\n", list[i].grade);
}
}
【问题讨论】:
-
为什么不在阅读时处理每一行,而不是将其复制到临时数组中?您的方法占用了两倍的内存,但没有明显的好处......
-
strcpy()不检查是否有空间。使用strcpyn() -
@Floris 我已经考虑过如何做到这一点,这是我能想到的最佳解决方案(我还是个新手)。你会怎么做?每一行都是结构中的一个新元素,5 行后它在数组结构中开始一个新元素。
-
我已经给出了一个如何在答案中做到这一点的例子(如下)。