【发布时间】:2011-10-31 04:45:04
【问题描述】:
对于每一行文本:
-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
提前感谢您的帮助!
@洛基
我改变了循环,所以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)\Microsoft Visual Studio 10.0\vc\include\vector”
【问题讨论】:
-
没什么花哨的。只需从文件中读取ifstream::read()每个结构并使用vector::push_back将其保存在向量中。
-
我已经将数据从文本文件中删除并放入向量中。它正在从我遇到问题的结构向量中获取保存的数据。
-
我添加了一个答案,希望对你有所帮助。
-
请多花点功夫格式化输入。阅读网站的标记部分。 stackoverflow.com/editing-help。请注意,当您编辑/编写文本时,此链接可通过编辑框右上角的问号获得。meta.stackexchange.com/q/74999/138817
-
@LokiAstari 我会确保下次这样做。感谢您这次修复它!