2015-09-14 64 views
-3

好吧,所以我正在從一個文件中讀取數據到C++中的Struct中,我有一個程序可以做到這一點。它讀取包含學生姓名,每個學生在班級中的成績以及每個學生的專業的文件。我試圖弄清楚的是如何收集和平均我存儲在我的Struct中的分數,並輸出平均值以及最高和最低分數。需要平均等級存儲在一個Struct C++

我希望在這裏有人能給我一個正確的方向。任何幫助將不勝感激。

預先感謝您!

這是我到目前爲止有:

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 

struct studentInfo 
{ 
    string studentName; 
    double studentGrade; 
    string studentMajor; 
}; 

int main() 
{ 
    cout << "Please enter the file you wish to open:" << endl; 
    string fileName; 
    cin >> fileName; 

    ifstream infile; 
    infile.open(fileName.c_str()); 

    if (!infile) 
    { 
     cout << "Error! Cannot find specified file!" << endl; 

     return 1; 
    } 

    studentInfo array[11]; 
    int i; 

    for (int i = 0; i < 11; i ++) 
    { 
     infile >> array[i].studentName >> array[i].studentGrade >>array[i].studentMajor; 
    } 

    for (int i = 0; i < 11; i++) 
    { 
     cout << array[i].studentName << " "; 
     cout << array[i].studentGrade << " "; 
     cout << array[i].studentMajor << "\n "; 
    } 

    return 0; 
} 

以防萬一你想知道,正在讀入結構中的數據文件被格式化爲這樣的.dat文件:(studentName [標籤] studentGrade [標籤] studentMajor)

像這樣:

湯姆99 CS

克萊爾56 MAT

蘇96 CS

凱西88 MAT

詹姆斯45 CS

弗蘭克78 GS

奔52 ARCH

拉倫62 CS

哈利78是

薩姆100 CS

詹妮弗·68 MAT

回答

1

如何收集和平均I都存儲在我的結構和產量最高和最低等級

沿平均成績您已經將成績讀入studentInfo array[11];,並循環輸出它們:當您使用額外變量循環記錄totalminmax時,我nitialised分別爲0,array[0].studentgradearray[0].studentgrade:您可以使用+=累積總數,並使用if測試以有條件地將minmax替換爲較低/較高值。您可以通過將總數除以記錄數來輸出平均值。

+0

這是非常有幫助的,謝謝@TonyD – ebonymessiah

+0

@ebonymessiah不客氣 - 快樂編碼!乾杯。 –