1. 程式人生 > >檔案流(記憶體到檔案,檔案到記憶體,記憶體到螢幕)

檔案流(記憶體到檔案,檔案到記憶體,記憶體到螢幕)

功能,輸入到檔案,從檔案輸出到螢幕,然後統計輸出結果。

  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. ////
  25. ifstream ifile(filename,ios::in|ios::binary);
  26. if(!ifile)
  27. {cerr<<"open error"<<endl; 
  28. exit(1);}
  29. //getline(ifile,s1);
  30. //cout<<s1<<endl;
  31. //ifile.close();
  32. while(getline(ifile,s1))
  33.       {
  34. for(int i=0;i<s1.length();i++)
  35.       {
  36. if((s1[i]>='a'&&s1[i]<='z')||(s1[i]>='A'&&s1[i]<='Z'))
  37. wordcount++;
  38. else
  39.  {
  40. if(wordcount!=0)
  41.   { 
  42. temstr=s1.substr(i-wordcount,wordcount);
  43.   }
  44. ////如果容器不空,則查詢單詞是否存在
  45. for(j=0;j<v1.size();j++)
  46.                         if(temstr==v1[j].word)  
  47. {v1[j].num++;
  48.                  wordcount=0;/////從零開始記單詞的長度
  49.  break;
  50.                  }
  51. if(j>=v1.size())////表示不存在這個單詞
  52. {tem.word=temstr;
  53. tem.num=1;
  54. v1.push_back(tem);
  55. wordcount=0;
  56. // ifile.close();
  57. }
  58. }
  59.            }///end for
  60.       }////end while
  61. // 
  62.    ifile.close();
  63. ////列印單詞及出現次數
  64.    for(int i=0;i<v1.size ();i++)
  65.    cout<<"the word is:"<<v1[i].word<<", the times is:"<<v1[i].num<<endl;
  66. //
  67. }