對於文本的每一行:(會有線的未知量,每個尋找相同的格式)矢量,我不知道該怎麼辦
-Get first name
-Get last name
-Get Student Number
格式:
First Last 111111111
First Last 111111112
...
我想把每個學生放到自己的結構中。我已經設置了結構如下:
struct Student{
string lastName;
string firstName;
string stdNumber;
double assgn1;//doubles will be used later in prog.
double assign2;
double assign3;
double assign4;
double midTerm;
double finalGrade;
};
我的文件輸入功能如下:
int getFileInfo()
{
int failed=0;
ifstream fin;
string fileName;
vector<Student> students;
Student s; // A place to store data of one student
cout<<"Please enter the filename of the student grades (ex. filename_1.txt)."<<endl;
do{
if(failed>=1)
cout<<"Please enter a correct filename."<<endl;
cin>>fileName;
fin.open(fileName.c_str());// Open the file
failed++;
}while(!fin.good());
while (fin >> s.firstName >> s.lastName >> s.stdNumber)
students.push_back(s);
fin.close();
return 0;
}
在文件輸入,我做一個載體,但我不確定如何訪問它的每個單獨部分或學生s
,因爲它似乎只能讓一個學生。我被告知,文件的每一行都被分割並輸入到students
向量中,但我不知道如何提取該信息。我如何讓每個學生脫離students
向量並進入它自己的結構,這樣我就可以將每個學生用作它自己的結構? 所以,最後,我想成爲能夠輸出:
Student1: First Last 111111111
Student2: First Last 111111112
However More students are in the file
在此先感謝您的幫助!
@Loki 我改變了循環,所以loop != end
,我仍然得到同樣的問題。這裏是我的代碼:
int getFileInfo()
{
int failed=0;
ifstream fin;
string fileName;
vector<Student> students;// A place to store the list of students
vector<Student>::iterator loop = students.begin();
vector<Student>::iterator end = students.end();
Student s; // A place to store data of one student
cout<<"Please enter the filename of the student grades (ex. filename_1.txt)."<<endl;
do{
if(failed>=1)
cout<<"Please enter a correct filename."<<endl;
cin>>fileName;
fin.open(fileName.c_str());// Open the file
failed++;
}while(!fin.good());
while (fin >> s.firstName >> s.lastName >> s.stdNumber){
cout<<"Reading "<<s.firstName<<" "<<s.lastName<<" "<<s.stdNumber<<endl;
students.push_back(s);
}
fin.close();
for(loop;loop!=end;++loop)
cout<<loop->firstName<<" "<<loop->lastName<<" "<<loop->stdNumber<<endl;
return 0;
}
此外,Visual Studio是說vector iterators incompatible
,
指着 「C:\ Program Files文件(x86)的\微軟的Visual Studio 10.0 \ VC \包括\載體」
Nothing fancy.Just read [ifstream :: read()](http://www.cplusplus.com/reference/iostream/) istream/read /)來自該文件的每個結構,並使用[vector :: push_back](http://www.cplusplus.com/reference/stl/vector/push_back/)將其保存在向量中。 –
我已經將數據從文本文件中刪除並放入向量中。它從我遇到的結構向量中獲取保存的數據。 – b3orion
我加了一個答案,希望對你有所幫助。 –