使用聚合对象的“{..}”构建错误E0530初始化

时间:2018-04-30 16:09:37

标签: c++ arrays compiler-errors initialization

我正在尝试在这里创建一个大小为'i'的数组,其中i是先前定义的,(底部是完整代码)

double studentScores[] = new double[i];

但是我一直收到以下错误:

  

初始化为'{...}'预期。

我已经尝试过指针方法,但这似乎与我的其余代码不兼容。非常感谢任何帮助,谢谢你的时间。

int main()
{
    ifstream inData;                //input file stream variable
    ofstream outData;           //output file stream variable

    inData.open("Data.txt");        //open data file
    outData.open("testStatistics.out");

    int i = 0;
    while (inData.eof() == false)   //while you have not reached the end of the file
    {
        i++;                            //i == size of the class
    }
    double studentScores[] = new double[i];     //creates an array of the size of the number of inputs

    for (int j = 0; j < i; j++)
    {
        inData >> studentScores[j]; //read in student scores
    }

    double average1 = average(i, studentScores);
    double median1 = median(i, studentScores);

    int distribution[10] = { 0 };
    for (int v = 0; v < i; v++)         //increment distribution appropriately
    {
        int h = scoresDistribution(v, studentScores);
        distribution[h] ++;
    }

    outData << "There are " << i << "scores available." << endl;
    outData << "The average is : " << average1 << endl;
    outData << "The median is : " << median1 << endl;
    outData << "The detailed grade distribution is as follows : " << endl;

    outData << fixed << left;
    outData << setfill(' ') << setw(10) << "range" << setw(10) << " # of Students" << endl;
    int z = 100;
    int y = 90;
    for (int f = 0; f < 10; f++)
    {
        outData << setfill(' ');
        outData << setw(10) << "[" << z << " - " << y << "]";
        outData << distribution[f] << endl;
        z = z - 10;
        y = y - 10;
    }

    inData.close(); //close input data file
    outData.close(); //close output data file

    cout << "Press any key to quit…" << endl;

    cin.ignore(50, '\n');
    return 0;
}

1 个答案:

答案 0 :(得分:0)

double studentScores[] = new double[i];

这无效C++。这看起来像一个残忍的C++ / Java混合。

您无法在此处在堆栈上创建数组,因为这样做需要在编译时知道固定大小。

现代C++的最佳方式是使用std::vector

std::vector<double> studentScores;
studentScores.resize(i);

如果您必须使用new,则必须使用指针,因为这是new返回的内容:

double* studentScores = new double[i];

请注意,必须在您完成使用后自行释放该内存:

delete[] studentScores;

在任何一种情况下,如果&#34;似乎不适用于我的其余代码&#34; ,则需要修复其余的代码。您可能想要为此单独提出问题,或使用搜索来查找可以帮助您的问题。