2015-07-20 47 views
1

我的問題是,我已經建立了一個數組來存儲從文件中讀取值計算,總計。然後將這些存儲的總計加在一起以找到總體平均值。陣列不是while循環中正確初始化

此問題源於程序開始處的'cin',用戶輸入一個數字,並且該數字應該通過設置程序循環次數和數組內多少個模塊來驅動程序。無論我嘗試多少,該陣列似乎都不能正常工作。

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

using namespace std; 

int main() 
{ 
    string StudentGrades; 
    int studentID; 
    double quiz1; 
    double quiz2; 
    double quiz3; 
    double quiz4; 
int total = 0; 
double choice; 
ofstream outFile; 
double numStud=1; 

cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl; 
outFile.open("StudentGrades.txt"); 
cout << "How many students would you like to enter?" << endl; 
cin >> numStud; 

for (int x = 0; x < numStud; x++) 
{ 
    cout << "Enter student ID: "; 
    cin >> studentID; 
    cout << "Enter quiz grade 1: "; 
    cin >> quiz1; 
    //cout << quiz1; 
    cout << "Enter quiz grade 2: "; 
    cin >> quiz2; 
    //cout << quiz2; 
    cout << "Enter quiz grade 3: "; 
    cin >> quiz3; 
    //cout << quiz3; 
    cout << "Enter quiz grade 4: "; 
    cin >> quiz4; 
    //cout << quiz4; 
    cout << endl; 
    //outFile.open("StudentGrades.txt"); 
    if (outFile.is_open()) 
    { 
     cout << "inside if/else outFile" << endl; 
     //outFile << "File successfully open"; 

     outFile << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl; 

    } 
    else 
    { 
     cout << "Error opening file"; 
    } 
    outFile.close(); 
    /*cout << "Enter 0 for no more students. Enter 1 for more students." << endl; 
    cin >> choice; 
    if (choice == 1) 
     continue; 
    if (choice == 0) 
    { 
     outFile.close(); 
     break; 
    }*/ 

} 



ifstream inFile; 
inFile.open("StudentGrades.txt"); 
int sTotal; 
int total[numStud]; 
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4) 
{ 
    //cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl; 
    total = (quiz1 + quiz2 + quiz3 + quiz4); 
    sTotal = total[numStud]; 

    double avg = total/4; 


} 


system("pause"); 
return 0; 

}

+0

'INT總[numStud]'不是標準compilant C++ – Creris

回答

2

int total[numStud];variable length array並且不是在C++標準。如果你需要一個陣列,你不知道尺寸是多少,那麼你應該使用std::vector。一個向量幾乎可以像數組一樣使用。例如,你可以將變成:

int total; 
std::vector<int> studentTotal; 
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4) 
{ 
    //cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl; 
    studentTotal.push_back(quiz1 + quiz2 + quiz3 + quiz4); // insert into the vector at the end 
    total += studentTotal.back(); // get last inserted element 
} 
+0

你可以給我哪裏會去一個例子嗎? –

+0

@ConnorLance我編輯了我的答案給你一個小例子。 – NathanOliver

+0

它是什麼庫名稱,因爲它爲我創建錯誤 –