我的矢量不是從我有它檢索文件中獲取數據。我創建了一個名爲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
}
爲什麼需要打開文件兩次?爲什麼不打開一次,第一次閱讀學生?你會通過'newStudentVector.size()'知道有多少學生。 – PaulMcKenzie
你說得對,我甚至都沒有想過! –
在網上搜索「計算器C++讀取文件載體」。總是先研究。 –