数组未在while循环内正确初始化

时间:2015-07-20 18:57:25

标签: c++ arrays loops for-loop while-loop

我的问题是我已经设置了一个数组来存储根据从文件中读取的值计算的总数。然后将这些存储的总数加在一起以找到超过所有平均值。

这个问题源自一个' 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;

}

1 个答案:

答案 0 :(得分: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
}