如何讀取包含學生姓名和標記的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