对于文本的每一行:(会有线的未知量,每个寻找相同的格式)矢量,我不知道该怎么办
-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
我加了一个答案,希望对你有所帮助。 –