将文件中的数据读入矢量对象

时间:2016-12-16 03:08:49

标签: c++ file class object vector

我的矢量没有从我检索的文件中获取数据。我创建了一个名为Student的类,并且需要从中创建一个向量来为学生存储多个值。代码在我的原始测试文件上运行,但是当我更改学生时,它会出错。

以下是主要部分:

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
}

2 个答案:

答案 0 :(得分:0)

你必须打开你的字符串名称文件:

studentAnswers.open(filename.c_str());

尝试像这样遍历你的矢量:

getline(studentAnswers,line)
while (!studentAnswers.eof()) { 
    getline(studentAnswers,line)
    ++numStudents;
}

答案 1 :(得分:0)

假设您已实现operator>>(std::istream&, Student&),那么实现fillVector()的一种相当简单的方法是使用流迭代器。

void fillVector(std::vector<Student>& newStudentVector, 
                std::string filename, int& numStudents) {
    std::ifstream studentAnswers(filename);
    if (!studentAnswers) {
        std::cout << "WARNING! studentAnswers file not found\n";
    }
    newStudentVector.assign(
        std::istream_iterator<Student>(studentAnswers),
        std::istream_iterator<Student>());
    numStudents = newStudentVector.size();
}