如何读取包含学生姓名和标记的txt文件并将其输入到结构数组中。C文件处理/结构问题
maximum allowable records are 7: e.g. James 45 Mary 70 Rob 100
如何读取包含学生姓名和标记的txt文件并将其输入到结构数组中。C文件处理/结构问题
maximum allowable records are 7: e.g. James 45 Mary 70 Rob 100
发现此代码足够相似,应该能够帮助您完成所需的任务。
#include <stdio.h>
#include <string.h>
/* Sample data lines
5 0 Wednesday Sunny
6 2 Thursday Wet
*/
int main() {
/* Define a daydata structure */
typedef struct {
int n_adults; int n_kids;
char day[10]; char weather[10];
} daydata ;
daydata record[30];
FILE * filehandle;
char lyne[121];
char *item;
int reccount = 0;
int k;
/* Here comes the actions! */
/* open file */
filehandle = fopen("newstuff.txt","r");
/* Read file line by line */
while (fgets(lyne,120,filehandle)) {
printf("%s",lyne);
item = strtok(lyne," ");
record[reccount].n_adults = atoi(item);
item = strtok(NULL," ");
record[reccount].n_kids = atoi(item);
item = strtok(NULL," ");
strcpy(record[reccount].day,item);
item = strtok(NULL,"\n");
strcpy(record[reccount].weather,item);
printf("%s\n",record[reccount].day);
reccount++;
}
/* Close file */
fclose(filehandle);
/* Loop through and report on data */
printf("Weather Record\n");
for (k=0; k<reccount; k++) {
printf("It is %s\n",record[k].weather);
}
}
http://www.wellho.net/resources/ex.php4?item=c209/lunches.c
给人以代码叫喊,如果你有改变它以满足您的需求问题,你尝试过。
为什么这些矮子? – Orbit 2011-02-26 15:42:14
首先,定义结构。该结构描述了记录是什么;它包含哪些数据。在这里你有一个学生的名字和他或她的标志。
其次你需要准备数组来写入结构的对象。您从问题描述中已经知道,不允许超过7名学生,因此您可以定义该数组的长度。
接下来,打开文本文件。
最后编写一个循环,从文件中输入一个字符串作为学生的姓名和一个整数(或者如果您愿意,选择一个浮点数)作为标记。在循环中为每个记录创建一个结构并将结构插入到数组中。
当然,不要忘了在完成后关闭文件。
就是这样。如果您有任何语法或逻辑问题,请在评论中提问,我们很乐意提供帮助。
阅读手册页的fopen:http://linux.die.net/man/3/fopen
这应该给你的地方开始。
此外,fread和fgets的手册页可能会有所帮助。有很多方法可以从文件中读取,并且您选择的路径将取决于很多事情,例如文件的结构以及您在应用程序中需要的安全性。
功课,当然? – wilhelmtell 2011-02-26 15:34:18