gpt4 book ai didi

c++ - 错误 : Variable length array of Non-POD element type 'string'

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:39 40 4
gpt4 key购买 nike

在开始之前,我必须首先声明,我已经研究过针对此错误的可能解决方案。不幸的是,它们都与不使用数组有关,这是我项目的要求。另外,我目前正在学习 CS 入门类(class),所以我的经验几乎没有。

数组的用途是从文件中收集名称。因此,为了初始化数组,我计算了名称的数量并将其用作大小。问题是标题中所述的错误,但我仍然使用一维数组时看不到解决方法。

主要.cpp

    #include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <iostream>
#include "HomeworkGradeAnalysis.h"

using namespace std;

int main()
{
ifstream infile;
ofstream outfile;
infile.open("./InputFile_1.txt");
outfile.open("./OutputfileTest.txt");

if (!infile)
{
cout << "Error: could not open file" << endl;
return 0;
}

string str;
int numLines = 0;

while (infile)
{
getline(infile, str);
numLines = numLines + 1;
}
infile.close();
int numStudents = numLines - 1;
int studentGrades[numStudents][maxgrades];
string studentID[numStudents];

infile.open("./InputFile_1.txt");

BuildArray(infile, studentGrades, numStudents, studentID);

infile.close();
outfile.close();
return 0;
}

HomeworkGradeAnalysis.cpp

    using namespace std;

void BuildArray(ifstream& infile, int studentGrades[][maxgrades],
int& numStudents, string studentID[])
{
string lastName, firstName;
for (int i = 0; i < numStudents; i++)
{
infile >> lastName >> firstName;
studentID[i] = lastName + " " + firstName;
for (int j = 0; j < maxgrades; j++)
infile >> studentGrades[i][j];
cout << studentID[i] << endl;
}
return;
}

HomeworkGradeAnalysis.h

    #ifndef HOMEWORKGRADEANALYSIS_H
#define HOMEWORKGRADEANALYSIS_H

const int maxgrades = 10;

#include <fstream>

using namespace std;

void BuildArray(ifstream&, int studentGrades[][maxgrades], int&, string studentID[]);
void AnalyzeGrade();
void WriteOutput();

#endif

文本文件格式简单:

    Boole, George   98    105    0    0    0    100    94    95    97    100

每一行都是这样,学生人数不等。

还有什么方法可以在使用数组的同时流式传输学生姓名?

最佳答案

数组必须用常量值声明,不能使用变量。如果您想使用变量声明它,则必须使用动态分配的数组。

string studentID[numStudents]; //wrong

string *studentID = new string[numStudents]; //right

编辑:一定要在完成后释放数组

delete [] studentID

关于c++ - 错误 : Variable length array of Non-POD element type 'string' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461424/

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