![]() |
#2
rjsp2011-12-30 11:50
![]() #include <string> #include <iostream> class Student { friend std::istream& operator>>( std::istream& is, Student& s ); friend std::ostream& operator<<( std::ostream& os, const Student& s ); public: Student() : id(-1) { } Student( const std::string& name_, int id_, char gender_, const std::string& faculty_ ) : name(name_), id(id_), gender(gender_), faculty(faculty_) { } std::string getname() const { return name; } int getid() const { return id; } char getgender() const { return gender; } std::string getfaculty() const { return faculty; } private: std::string name; int id; char gender; std::string faculty; }; std::istream& operator>>( std::istream& is, Student& s ) { std::string name; int id; std::string gender; std::string faculty; is >> name >> id >> gender >> faculty; if( is ) { s.name = name; s.id = id; s.gender = (gender=="男"?'M':'F'); s.faculty = faculty; } return is; } std::ostream& operator<<( std::ostream& os, const Student& s ) { os << s.name << ' ' << s.id << ' ' << (s.gender=='M'?"男":"女") << ' ' << s.faculty; return os; } #include <algorithm> #include <vector> #include <fstream> #include <iterator> using namespace std; int main() { ifstream in("name.txt"); if( in ) { vector<Student> Students; copy( istream_iterator<Student>(in), istream_iterator<Student>(), back_inserter(Students) ); copy( Students.begin(), Students.end(), ostream_iterator<Student>(cout,"\n") ); } return 0; } |
比如txt叫"name.txt",然后内容是:
小明 111 男 FIT
小丽 212 女 FOM
小王 516 男 FOE
小张 426 男 FCM
声明一个类,然后将这些数据保存在类的private成员中。
类的private成员有4 个;
string name;
int id;
char gender;
string faculty;
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;
class Student
{
string name;
string gender;
string faculty;
int id;
public:
Student(string name, int id, string gender, string faculty);
string getname(){return name;};
string getgender(){return gender;};
string getfaculty(){return faculty;};
int getid(){return id;};
};
int main()
{
ifstream in("name.txt");
string name;
string faculty;
string gender;
int id;
vector<string> vect;
while(getline(in, name, '\n'))
vect.push_back(name.substr(0, name.find(' ')));
vector<string>::iterator it=unique(vect.begin(), vect.end());
copy(vect.begin(), it, ostream_iterator<string>(cout, "\n"));
return 0;
}
应该要怎样继续??