gpt4 book ai didi

c++ - 生成错误E0530初始化,预期聚合对象使用 '{..}'

转载 作者:行者123 更新时间:2023-12-02 11:13:02 25 4
gpt4 key购买 nike

我正在尝试在此处创建大小为``i''的数组,其中我之前已定义(底部完整代码)

double studentScores[] = new double[i];

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

initialization with '{...}' expected.



我尝试了指针方法,但是似乎无法与我的其余代码一起使用。任何帮助将不胜感激,谢谢您的时间。
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;
}

最佳答案

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;

在这两种情况下,如果“这似乎与我的其余代码都不起作用”,则需要修复其余的代码。您可能要问一个单独的问题,或使用搜索找到可以帮助您的问题。

关于c++ - 生成错误E0530初始化,预期聚合对象使用 '{..}',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com