2017-06-17 167 views
-4

因此就出現了我過去的一個類有鑑於此項目中,用戶會閱讀的文本文件(讓稱它爲「studentstuff.txt」,見下文)讀取和修改txt文件(逐行)

*studentstuff.txt* 

1 
Bob Smith 
24 
3.5 
2 
Jill Williams 
23 
3.6 
3 
Tom Jones 
32 
2.4 
4 
Julie Jackson 
21 
3.1 
5 
Al Brown 
23 
3.35 
6 
Juan Garcia 
22 
3.4 
-7 
Melissa Davis 
20 
3.2 
8 
Jack Black 
44 
1.1 

並輸出結果:1)學生數量2)平均年齡3)平均gpa。在這個作業,我們有一個結構:

typedef struct{ 
    int id; 
    char name[255]; 
    int age; 
    float gpa; 
}student; 

根據該計劃,「studentstuff.txt」將根據結構再經過一些小的數學和功能吐出閱讀並排序

  • 學生的 '#':

  • 平均年齡:

  • 平均GPA:

問題是我的想法在我腦海中,但我似乎不能將它放入代碼。任何人都可以幫我解決這個問題嗎?

+5

至少在你不能放入C的代碼周圍提供[mcve]。 main(),scan&Co,printf。然後參加[遊覽],特別是[問]。 – Yunnosch

+0

我看不到需要排序。但是如果排序只是爲了好玩,結果應該覆蓋輸入文件嗎?標題似乎說「一行一行」,這不符合排序等整個文件操作。而且,只要你以後不覆蓋整個文件,也不會發生「修改」。 – Yunnosch

回答

0

與任何編程問題一樣,第一個動作(決定輸入和輸出之後)是將問題分解爲簡單的離散步驟。

這樣的一組的用於有機磷農藥問題的步驟將類似於:

open the input file 
if any errors: 
    output user message to stderr 
    exit program, indicating error occurred 
else 
    begin: loop: 
     input the info for one student 
     if any errors, except EOF: 
      output user message to stderr 
      cleanup by closing the input file 
      exit program, indicating an error occurred 
     else 
      update number of students 
      update total age 
      update total gpa 
     endif 
     goto top of loop 
    end loop: 
endif 

calculate the average age 
calculate the average gpa 

display number of students 
display average student age 
display average student gpa 

cleanup by closing the input file 
return to caller, indicating success 

由於計算將產生的級分,以避免出現問題,建議的結構被定義爲:

struct studentStruct 
{ 
    float id; 
    char name[255]; 
    float age; 
    float gpa; 
}; 

typedef struct studentStruct student; 

注意結構定義與typedef語句的分離。在這裏沒有任何區別,但是在使用調試器(需要struct標記名來正確顯示結構中的所有字段)以及使用大型項目​​以避免混淆時纔會有所作爲。