2016-03-02 21 views
-5

我們得到了一個任務,讓程序讀取我們的文本文件(姓名,學號,課程,年份,部分等等..但我似乎無法讓它工作,你能告訴我什麼是錯的嗎?無法讀取我寫的文件(C編程學生數據庫)

#include <windows.h> 
#include <conio.h> 
#include <stdio.h> 

struct record 
{ 
     char name[50],number[50],course[50],gender; 
     int year, section; 
     float midterm,final,average,sum; 
}; 

int main() 
{ 
    int a=1,n; 
    int passed=0,failed=0; 

    FILE *fp; 
    fp = fopen("StudentPUP.txt","r"); 

    if(fp==NULL) 
    { 
      printf("ERROR!"); 
      getch(); 
    } 

    struct record student[25]; 

    printf("Please input the number of students: "); 
    scanf("%d", &n); 

    for(a=0;a<n;a++) 
    { 
      fscanf(fp, "%f", student[a].average);// I CANNOT MAKE THE FSCANF WORK!!// 
    } 

    getch();   
} 

This是寫在我的文本文件裏面。輸入文件的

前幾行:

Student Name: Mark Benedict D. Lutab 
Gender: M 
Student Number: 2015-04711-MN-0 
Course: BSIT 
Year: 1 
Section: 2 
Midterm Grade: 2.00 
Final Grade: 1.75 
Average Grade: 1.8 

Student Name: Andrea Zoelle S. Jacinto 
Gender: F 
Student Number: 2015-04711-MN-0 
    <etc.> 
+0

如果您不只是在鍵入'c'時標記出現的每種編程語言,都會很感激。 – miradulo

+5

不應該是'fscanf(fp,「%f」,&(student [a] .average));'? –

+2

根據您必須閱讀的內容,您必須處理文件內容,即您存儲哪種格式的詳細信息。 –

回答

2

應該

fscanf(fp, "%f", &student[a].average); 

,而不是

fscanf(fp, "%f", student[a].average); 

但是,這可以讓你只讀取包含數字的文件,例如:

1.5 
1.9 
2.7 

要讀取的文件更加完整。

因此,在您的for循環中,您需要讀取10行,從每行中提取相關信息,將該信息存儲在記錄的相應字段中,並將記錄存儲在某處。

0

因爲它看起來像你的家庭作業,我不會給你解決方案,但我告訴你哪裏是錯誤。

您正在以不正確的方式使用fscanf。這條線:

fscanf(fp, "%f", &student[a].average); 

告訴這樣的: 「拿someValue中(float類型),並將其寫入學生[A]。平均」。 它不能在你的情況下工作,因爲你的數據結構更加完善。

你要做什麼? 首先,嘗試從輸出文件中寫入所有數據。 之後,你應該嘗試解析你感興趣的線:)

閱讀關於getline,sscanf。它可能對你很有幫助:)

1

你需要考慮輸入文件格式。 當您撥打fscanf時,「光標」位於文件的第一行。你需要做的是將光標移動到你想要閱讀的行上。

Student Name: Mark Benedict D. Lutab <-- cursor is located at the beginning of this line 
Gender: M 
Student Number: 2015-04711-MN-0 
Course: BSIT 
Year: 1 
Section: 2 
Midterm Grade: 2.00 
Final Grade: 1.75 
Average Grade: 1.8 <-- you need the cursor here 

爲了達到這個目的,您可以在while循環中使用fgets以去掉所需行之前的行。

char line[256]; 
while(fgets(line, 256, fp) && line[0] != 'A'); // line[0] != 'A' makes the loop stop when it reached the desired line 

現在您的光標位於所需的行上,但您需要擺脫要讀取的值前面的文本。

Average Grade: 1.8 <-- get rid of "Average Grade: " 

的好處是line已經包含了這一行,所以你可以使用sscanf來讀取該字符串格式化。

sscanf(line, "%*s %*s %f", &student[0].average); // note the ampersand in front of student[0].average to get its address 

使用%*s使得sscanf忽略詞「平均」和「等級:」所以%f將讀取所需的值。

+0

謝謝我已完成中期,最終和平均成績的價值,但如果我嘗試獲得「Mark Benedict D. Lutab」的名稱,它只會得到「Mark」,如何我能解決這個問題嗎? –

+0

查找所需的行並將其存儲在字符串中搜索冒號。建立一個從冒號後面開始的子串,直到你存儲的字符串結束。關於C中的子字符串的信息可以在你的朋友的幫助下找到google – muXXmit2X

+0

@BenedictLutab _if我試圖得到名字「Mark Benedict D. Lutab」,它只能得到「Mark」,我該如何解決this_:這需要一個新的題。 –