文件流(内存到文件,文件到内存,内存到屏幕)

功能,输入到文件,从文件输出到屏幕,然后统计输出结果。

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. using namespace std;
  6. typedef struct{
  7.  string word;
  8.  int num;
  9. }count;
  10. void main()
  11. {
  12. int wordcount=0,j=0;
  13.     char *filename="E:\\统计单词的个数.txt";
  14. string s1,temstr;
  15. count tem;
  16. tem.num=0;
  17. vector<count> v1;  //定义count类型的向量,动态存储count变量
  18. ofstream ofile;
  19. ofile.open(filename);
  20. /向文件输出字符
  21. for(int i=0;i<10;i++)
  22. ofile<<"fan jing"<<endl;
  23. ofile.close();

  24. ifstream ifile(filename,ios::in|ios::binary);
  25. if(!ifile)
  26. {cerr<<"open error"<<endl; 
  27. exit(1);}

  28. //getline(ifile,s1);
  29. //cout<<s1<<endl;
  30. //ifile.close();


  31. while(getline(ifile,s1))
  32.       {
  33. for(int i=0;i<s1.length();i++)
  34.       {
  35. if((s1[i]>='a'&&s1[i]<='z')||(s1[i]>='A'&&s1[i]<='Z'))
  36. wordcount++;
  37. else
  38.  {
  39. if(wordcount!=0)
  40.   { 
  41. temstr=s1.substr(i-wordcount,wordcount);
  42.   }
  43. 如果容器不空,则查找单词是否存在
  44. for(j=0;j<v1.size();j++)
  45.                         if(temstr==v1[j].word)  
  46. {v1[j].num++;
  47.                  wordcount=0;/从零开始记单词的长度
  48.  break;
  49.                  }
  50. if(j>=v1.size())表示不存在这个单词
  51. {tem.word=temstr;
  52. tem.num=1;
  53. v1.push_back(tem);
  54. wordcount=0;
  55. // ifile.close();
  56. }
  57. }
  58.            }///end for
  59.       }end while
  60. // 
  61.    ifile.close();
  62. 打印单词及出现次数
  63.    for(int i=0;i<v1.size ();i++)
  64.    cout<<"the word is:"<<v1[i].word<<", the times is:"<<v1[i].num<<endl;
  65. //
  66. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值