【发布时间】:2016-12-16 03:08:49
【问题描述】:
我的向量没有从我检索的文件中获取数据。我创建了一个名为 Student 的类,需要从中创建一个向量来为学生存储多个值。该代码适用于我的原始测试文件,但是当我更改学生时,它会出错。
这是 main 中的部分:
vector<Student> studentVector; //creating a vector using the defined class Student
string userFile = "";
string filename = "";
int numStudents = 0; //total number of students
int numQuestions = 0; //total number of questions
string key = ""; //answer key
cout << "Enter the name of the file: ";
cin >> userFile; //get name of file from user
filename = checkFile(userFile, numQuestions, key); //gets info from file and returns the new file name to get student answers
fillVector(studentVector, filename, numStudents); //fills vector with values from file
这是读取数据的函数:
void fillVector(vector<Student>& newStudentVector, string filename, int& numStudents) {
ifstream studentAnswers; //read mode file
string line = ""; //used to read lines
int id = 0;
string fName = ""; //first name
string lName = ""; //last name
string answers = "";
studentAnswers.open(filename); //opens file using filename passed into function
while (getline(studentAnswers,line)) {
++numStudents; //reads the number of lines in file
}
studentAnswers.close(); //closed file because it reached end of file
studentAnswers.open(filename); //reopens file
for (int i = 0; i < numStudents; i++) {
//reads file data
studentAnswers >> id;
studentAnswers >> fName;
studentAnswers >> lName;
studentAnswers >> answers;
Student newStudent(id, (fName + " " + lName), answers, 100.00, "A"); //creates a new object
newStudentVector.push_back(newStudent); //adds new vector with newStudent data
}
studentAnswers.close(); //close file
}
【问题讨论】:
-
为什么要打开文件两次?为什么不打开一次,第一次读学生呢?通过
newStudentVector.size(),您将知道有多少学生。 -
你说得对,我根本没想到!
-
在互联网上搜索“stackoverflow c++ 读取文件向量”。始终先研究。
-
@ThomasMatthews 我已经进行了研究,但没有找到问题的答案。我的问题是为什么向量在第一次测试给我数据时没有得到新测试的数据?
-
你怎么知道(我们怎么知道)向量没有得到数据?我没有看到你在任何地方测试或展示它。请将您的原始程序缩减为能够说明问题的最小的完整程序。然后edit您的问题将简短而完整的程序复制粘贴到您的问题中。请包括您的程序的实际和预期输出。请参阅minimal reproducible example 了解更多信息。
标签: c++ file class object vector