檔案流(記憶體到檔案,檔案到記憶體,記憶體到螢幕)
阿新 • • 發佈:2019-02-17
功能,輸入到檔案,從檔案輸出到螢幕,然後統計輸出結果。
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- using namespace std;
- typedef struct{
- string word;
- int num;
- }count;
- void main()
- {
- int wordcount=0,j=0;
- char *filename="E:\\統計單詞的個數.txt";
- string s1,temstr;
- count tem;
- tem.num=0;
- vector<count> v1; //定義count型別的向量,動態儲存count變數
- ofstream ofile;
- ofile.open(filename);
- /////向檔案輸出字元
- for(int i=0;i<10;i++)
- ofile<<"fan jing"<<endl;
- ofile.close();
- ////
- ifstream ifile(filename,ios::in|ios::binary);
- if(!ifile)
- {cerr<<"open error"<<endl;
- exit(1);}
- //getline(ifile,s1);
- //cout<<s1<<endl;
- //ifile.close();
- while(getline(ifile,s1))
- {
- for(int i=0;i<s1.length();i++)
- {
- if((s1[i]>='a'&&s1[i]<='z')||(s1[i]>='A'&&s1[i]<='Z'))
- wordcount++;
- else
- {
- if(wordcount!=0)
- {
- temstr=s1.substr(i-wordcount,wordcount);
- }
- ////如果容器不空,則查詢單詞是否存在
- for(j=0;j<v1.size();j++)
- if(temstr==v1[j].word)
- {v1[j].num++;
- wordcount=0;/////從零開始記單詞的長度
- break;
- }
- if(j>=v1.size())////表示不存在這個單詞
- {tem.word=temstr;
- tem.num=1;
- v1.push_back(tem);
- wordcount=0;
- // ifile.close();
- }
- }
- }///end for
- }////end while
- //
- ifile.close();
- ////列印單詞及出現次數
- for(int i=0;i<v1.size ();i++)
- cout<<"the word is:"<<v1[i].word<<", the times is:"<<v1[i].num<<endl;
- //
- }