错误:非POD元素类型“字符串”的变长数组 [英] Error: Variable length array of Non-POD element type 'string'
问题描述
开始之前,我必须先说,我已经看着这个错误可能的解决方案。不幸的是,它们都与没有使用数组,这是我的项目的要求做的。另外,我目前正在简介CS所以我的经验是旁边没有。
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
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
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?
推荐答案
这是数组必须用一个恒定值来声明,你不能用一个变量。如果你想使用宣布变数就必须使用动态分配的数组。
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
编辑:一定要释放阵列一旦你完成了它
Be sure to free the array once your finished with it
delete [] studentID
这篇关于错误:非POD元素类型“字符串”的变长数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!