Error: Variable length array of Non-POD element type 'string'
arrays, c++
Solution
An Array must be declared with a constant value, you can't use a variable. if you want to declared it using variables you must use a dynamically allocated array.
string studentID[numStudents]; //wrong
string *studentID = new string[numStudents]; //right
EDIT: Be sure to free the array once your finished with it
delete [] studentID
Problem
Before beginning, I must first say that I have already looked into possible solutions for this error. Unfortunately, they all have to do with not using arrays, which is a requirement for my project. Also, I'm currently taking Intro to CS so my experience is next to none. The purpose of the array is to gather names from a file. So in order to initialize array, I count the number of names and use it as the size. The problem is the error stated in the title, but I don't see a way around it while still using a 1D array. 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; } ``` 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 ``` The text files are of simple format: ``` Boole, George 98 105 0 0 0 100 94 95 97 100 ``` Each line is like this, with varying number of students. What is another method to which I can still stream the names of the students while still using an array?