错误:非 POD 元素类型的可变长度数组'string'

Error: Variable length array of Non-POD element type 'string'

本文关键字:数组 string POD 元素 类型 错误      更新时间:2023-10-16

在开始之前,我必须首先说,我已经研究了这个错误的可能解决方案。不幸的是,它们都与不使用数组有关,这是我的项目的要求。此外,我目前正在学习CS简介,所以我的经验是首屈一指的。

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

main.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;
    }

作业等级分析.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;
    }

作业成绩分析.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

可变长度数组不是该语言的标准特性。您必须在堆上进行分配,或者创建一个向量,或者使用一个常量。

此外。我从Clang收到了这个错误消息,而g++-4.9没有给我,编译也可以。所以它取决于编译器。