错误:非 POD 元素类型的可变长度数组'string'
Error: Variable length array of Non-POD element type 'string'
在开始之前,我必须首先说,我已经研究了这个错误的可能解决方案。不幸的是,它们都与不使用数组有关,这是我的项目的要求。此外,我目前正在学习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没有给我,编译也可以。所以它取决于编译器。
相关文章:
- 创建 std::string 的二维数组的最佳做法
- <string> 如何在使用 SWIG 时将 int 数组和 List 作为参数传递给 C# C++
- 使用 .data() 将字符数组转换为 std::string 不会转换整个数组
- 如何正确删除 std::string 数组
- 将空填充但不以空结尾的固定长度字符数组转换为 std::string 的最佳方法
- "Error reading character of string" 为哈希动态增长数组的问题 (C++)
- 将C 数组写成文件,避免创建std :: String
- 使用STD :: String和字符数组之间的选择
- 将字符数组转换为 std::string 以传递到 std::bitset seg 错误
- 将 std::string 重新解释为无符号的 int 数组
- std::string 参数是如何从原始字符数组文本传递的
- C++将向量转换为<string>无符号字符数组
- 数据结构对齐:为什么Char和STD :: String的数组不同
- 尝试使用Huffman String代码更新数组
- C++:矢量<string>到字符数组
- 如何将包含 '