求教 用C++编一个程序
用C++编一个程序
题目是这样的:
编一个程序能把名片上所有的信息都保存到一个文件上,并且能通过名片上的""公司名和"姓名"查找到文件中名片的所有的信息.
请各位大虾帮帮忙!先谢了!!!
[解决办法]
这个可以从文件中读出名片并搜索. 名片只有公司名和人名信息
- C/C++ code
#include <iostream>#include <fstream>#include <iterator>#include <list>#include <string>#include <algorithm>using namespace std;struct Card{ string CompanyName; string Name;};istream& operator >>(istream& in, Card& c){ in>>c.CompanyName>>c.Name; return in;}ostream& operator <<(ostream& out, const Card& c){ out<<c.CompanyName<<' '<<c.Name; return out;}class CardCmp{public: enum COMPTYPE {COMPANY, PERSON}; CardCmp(const string& s, COMPTYPE type = COMPANY): strName(s),cmpType(type) {} bool operator ()(const Card& c) { return (cmpType == COMPANY)? (strName == c.CompanyName) : (strName == c.Name); }private: string strName; COMPTYPE cmpType;};void card(){ list<Card> lstCard; list<Card>::iterator pos; fstream fs("card.txt"); istream_iterator<Card> ifs_iter(fs); istream_iterator<Card> ifs_end; copy(ifs_iter, ifs_end, back_inserter(lstCard)); for (pos = lstCard.begin(); pos != lstCard.end(); ++pos) { cout<<*pos<<endl; } string s; cout<<"Please inpu company name:\n"; cin>>s; pos = find_if(lstCard.begin(), lstCard.end(), CardCmp(s)); if (pos != lstCard.end()) { cout<<"founded :"<<*pos<<endl; } else { cout<<"not found"<<endl; } cout<<"Please inpu company name:\n"; cin>>s; pos = find_if(lstCard.begin(), lstCard.end(), CardCmp(s, CardCmp::PERSON)); if (pos != lstCard.end()) { cout<<"founded :"<<*pos<<endl; } else { cout<<"not found"<<endl; } fs.close();}