65,210
社区成员
发帖
与我相关
我的任务
分享
/*
设置一个电话本,里面的联系人必须定义为类,从磁盘中的文件中读取联系人,格式为每行一条联系人记录,姓名和电话号码用逗号(,)分割,姓名在前。例如:“zhangsan, 4567”就是一行记录;重载>>实现这个功能。
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Concact
{
private:
string name;
string phonenumber;
public:
friend fstream& operator >>(fstream & , Concact &); //重载>>操作符,用来从文件中读取数据到对象中
};
fstream & operator >>(fstream & is , Concact &T )
{
int i = 0, j = 0;
string temp;
getline(is, temp); //从文本中读取一行
i = temp.find(","); //找到,的位置
T.name = temp.substr(0,i ); //把,以前的内容赋值给name
j = temp.find("\n");
T.phonenumber = temp.substr(i+1,j); //剩下的赋值给phonenumber
return is;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
Concact temp;
vector<Concact> Phonebook; //定义一个容器,元素为一个联系人对象
fstream archieve("abc.txt");
while(!archieve.eof())
{
archieve>>temp;
Phonebook.push_back(temp); //读取联系人到容器中
}
archieve.close();
cout<<Phonebook.size(); //打印显示总是比实际数目大1
return 0;
}
archieve>>temp;
while(!archieve.eof())
{
Phonebook.push_back(temp); //读取联系人到容器中
archieve>>temp;
}