從一個txt檔案中讀取文章並刪除特定單詞並顯示文章

來源:互聯網
上載者:User

/*本程式練習從一個文字檔中逐單詞讀出字串,並將它們儲存在一個vector<string>中,最終刪除其中的
and,the,a,if ,or,but等無意義的單詞,最後顯示出來。
*/
#include<string>
#include<iostream>
#include<vector>
#include <fstream>
#include<algorithm>
//本來有N多錯誤的,加上這個fstram的標頭檔就好了,fstream包含iostream.以後可以用#include <fstream>來代替#include<iostream>哈
using namespace std;

//本函數從檔案中讀出資料,並寫入到string vector中,返回 string vector
vector<string>* readandstore()
{
 string file_name,text_words;
 int count_words=0;
 cout<<"請輸入要讀出的檔案名稱"<<endl;
 cin>>file_name;
 ifstream infile(file_name.c_str ());
 
 
 if(!infile)
 {
  cerr<<"開啟指定檔案失敗"<<endl;
  exit(-1);
 }
 vector<string>* myvector=new vector<string>;//動態建立一個string vector,避免空懸指標
 while(infile>>text_words)
 {
  myvector->push_back (text_words);
  count_words++;
 }
 cout<<"共有"<<count_words<<"個單詞"<<endl;
 infile.close ();
 return myvector;
}
//本函數輸出  string vector中的單詞
void print(vector<string> *p)
{
 vector<string>::iterator begin_iter=p->begin ();
 for(;begin_iter!=p->end ();begin_iter++)
 {
  cout<<*begin_iter<<"/t";
 }

}

//本函數從string vector 中刪除一些沒有意義的單詞
void deletewords(vector<string> *p)
{
 string sc[]={"and","the","a","if","or","but"};
 int numbers=0;
 vector<string>remove_words(sc,sc+6);
 for(vector<string>::iterator iter=remove_words.begin ();iter!=remove_words.end ();iter++)
 {
  numbers=count(p->begin (),p->end (),*iter);
  // 泛型演算法count的使用,統計有多少個與*iter相等的單詞
  vector<string>::iterator flag;
  flag=remove(p->begin (),p->end (),*iter);
  p->erase (flag,p->end ());
  cout<<"/n有"<<numbers<<"個"<<*iter<<"被刪除:"<<endl;
 }

}

void main()
{
 vector<string> *p;
 p=readandstore();
 cout<<"刪除以前檔案內容為:"<<endl;
 print(p);
 deletewords(p);
 cout<<"刪除以後檔案內容為:"<<endl;
 print(p);
 cout<<endl;
 cout<<"刪除後還有"<<p->size ()<<"個單詞"<<endl;
}

/*總結:
(1)練習了對檔案的輸出用ifstream infile(檔案名稱),在對檔案讀取的時候,string text_words;
     infile>>text_words,就可將讀取的單詞儲存到text_words了。
(2)其次練習了使用泛型演算法count,remove,erase等。
(3)練習了對容器vector的使用,和對迭代器iterator的使用.
(4)明白了輸入檔案名稱的時候,必須是全路徑,如:d:/ttbc.txt
(5)在讀取單詞的時候,首先用的是getline(getline(infile,text_words,'/t'),後面發現getline
     是一次讀取一行,不能對單個單詞操作,即使我後面第三個參數用的是/t.
(6)讓我注意到開啟檔案要用close來關閉。
(7)開啟的檔案僅局限與txt檔案,開啟doc和rm檔案時開啟失敗。有空還要研究一下怎麼開啟其他檔案。
*/

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.