使用輸入輸出流迭代器讀取和寫入文件
目標(biāo)1:使用istream_iterator讀取一個(gè)文件的內(nèi)容(為數(shù)字),使用ostream_iterator將奇數(shù)寫入第一個(gè)文件中,每個(gè)值之后都跟一個(gè)空格;將偶數(shù)寫入第二個(gè)文件中,每個(gè)值占一行。
#include#include#include#include#includeint?main()
{
????ifstream?infile("numbers.txt");//創(chuàng)建文件輸入流,指向numbers.txt,此文件需要首先保存在工程目錄下
????ofstream?outfile_1("jishu.txt");//創(chuàng)建文件輸出流1,指向jishu.txt
????ofstream?outfile_2("oushu.txt");//創(chuàng)建文件輸出流2,指向oushu.txt
????if(!infile|!outfile_1|!outfile_2)//檢查文件是否存在
????{
??????cout<<"file?does't?exist?!"<<endl;
??????return?-1;
????}
????istream_iteratorin_iter(infile),eof;//創(chuàng)建輸入流迭代器,指向infile,eof用于判斷文件末尾
????ostream_iteratorout_iter_1(outfile_1,"?");//創(chuàng)建輸出流迭代器,每個(gè)元素后跟空格
????ostream_iteratorout_iter_2(outfile_2,"n");//創(chuàng)建輸出流迭代器,每個(gè)元素后跟換行
????vectorvec(in_iter,eof);//將輸入流讀取的文件內(nèi)容復(fù)制到vec中
????for(auto?p=vec.begin();p!=vec.end();p++)
????{
??????if(*p%2==1)//數(shù)據(jù)為奇數(shù)
??????????copy(p,p+1,out_iter_1);
??????else//數(shù)據(jù)為偶數(shù)
??????????copy(p,p+1,out_iter_2);
????}
????system("pause");
???return?0;
}目標(biāo)2:讀取一個(gè)文檔中單詞出現(xiàn)的次數(shù),要求使用關(guān)聯(lián)容器map.
#include#include#include#include#includeusing?namespace?std;
int?main()
{
??mapword_count;//創(chuàng)建關(guān)聯(lián)容器
??string?word;
??ifstream?ifile("words.txt");//打開文件
??if(!ifile)//對(duì)文件進(jìn)行檢查
??{
?????cout<<"Can't?open?the?file!"<<endl;
?????exit(0);
??}
??istream_iteratoriter(ifile),eof;//創(chuàng)建輸入流迭代器,指向打開的文件
??auto?p=iter;
??while(p!=eof)//遍歷文件,對(duì)單詞進(jìn)行計(jì)數(shù)
??{
??????word=*p++;
??????++word_count[word];
??}
??for(auto?w=word_count.begin();w!=word_count.end();w++)
??????cout<first<<"?occurs?"<second<second>1)?"?times":"?time")<<endl;//向屏幕輸出每個(gè)單詞出現(xiàn)的次數(shù)
??system("pause");
??return?0;
}測(cè)試時(shí)先要在工程目錄先新建words.txt文件
寫文件:
[cpp]?view plain?copy#include?





