Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1481520
  • 博文数量: 148
  • 博客积分: 2234
  • 博客等级: 大尉
  • 技术积分: 3225
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-17 21:34
个人简介

未来很长。

文章存档

2017年(7)

2016年(4)

2015年(1)

2014年(6)

2013年(31)

2012年(99)

分类: C/C++

2012-05-25 21:14:36

本程序主要是温习一下vector容器的用法:

点击(此处)折叠或打开

  1. #include<iostream>
  2. #include<string>
  3. #include<fstream>
  4. #include<vector>

  5. #include<cassert>
  6. using namespace std;

  7. template <typename Info>

  8. class LoginLog
  9. {
  10.     public:
  11.         void build(std::string filename);
  12.         int search(Info item) const;
  13.         void display(std::ostream &out) const;
  14.     private:
  15.         vector<Info> myUserLog;
  16. };

  17. template <typename Info>
  18. void LoginLog<Info>::build(string filename)
  19. {
  20.     ifstream fin(filename.data());
  21.     assert(fin.is_open());
  22.     Info userInfo;
  23.     for(;;)
  24.     {
  25.         fin>>userInfo;
  26.         if(fin.eof()) break;
  27.         int pos=search(userInfo);
  28.         if(pos==myUserLog.size())
  29.             myUserLog.push_back(userInfo);
  30.     }
  31. }
  32. template <typename Info>
  33. int LoginLog<Info>::search(Info item) const
  34. {
  35.     int i;
  36.     for(i=0;i<myUserLog.size();i++)
  37.         if(item==myUserLog[i])
  38.             break;
  39.         return i;
  40. }

  41. template <typename Info>
  42. inline void LoginLog<Info>::display(ostream &out) const
  43. {
  44.     for(int i=0;i<myUserLog.size()-1;i++)
  45.         out<<myUserLog[i]<<endl;
  46. }
  47. int main(void)
  48. {
  49.     string userInfoFile;
  50.     char buffer[9];
  51.     ofstream outFile;
  52.     outFile.open("Log.txt");//在当前工作目录下创建一个文档
  53.     if(!outFile.is_open())
  54.     {
  55.         cout<<"Could not opened!";
  56.         return -1;
  57.     }
  58.     cout<<"now input the content of the log ,(input ok to end ) "<<endl;
  59.     for(;;)//往文件中写内容
  60.     {
  61.         
  62.         cin.getline(buffer,9);
  63.         outFile<<buffer;
  64.         outFile<<"\n";
  65.         if(strcmp(buffer,"ok")==0)
  66.             break;
  67.     }
  68.     outFile.close();
  69.     cout<<"Enter name of login-info file:";
  70.     getline(cin,userInfoFile);
  71.     
  72.     LoginLog<string> userIdLog;

  73.     userIdLog.build(userInfoFile);

  74.     cout<<"\n List of distinct user-ids who logged in :\n";

  75.     userIdLog.display(cout);
  76. }

阅读(1074) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~