第十四周項目一 小玩文件(文本文件的讀寫)

(1)

項目要求

(1)下面程序的功能是統計文本文件abc.txt中的字符個數,請填空將程序補充完整。

#include <iostream>
#include <cstdlib>
#include _____________ // (1)
using namespace std;
int main()
{
    fstream file;
    file.open("abc.txt", _________); // (2)
    if(!file) {
        cout<<"abc.txt can’t open."<<endl;
        exit(1);
    }
    char ch;
    int i=0;
    while( _____________) // (3)
    {
        file.get(ch);
         _____________; // (4)
    }
    cout<<"Character: "<<i<<endl;
    file._____________;// (5)
    return 0;
}


代碼如下

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
    {
    fstream file;
    file.open("abc.txt",ios::in); // (2)
    if(!file)
        {
        cout<<"abc.txt can’t open."<<endl;
        exit(1);
        }
    char ch;
    int i=0;
    while(!file.eof() ) // (3)
        {
        file.get(ch);
        i++; // (4)
        }
    cout<<"Character: "<<i<<endl;
    file.close();// (5)
    return 0;
    }


運行結果

當沒建立abc.txt時:


建立了abc.tct:




(2)

項目要求

下面程序的功能是將文本文件abc.txt中的所有行加上行號後寫到newabc.txt文件中,請填空將程序補充完整。

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
    fstream outfile,infile;
    infile.open("abc.txt",_________); // (1)
    if(!infile) {
        cout<<"Can’t open the file."<<endl;
        abort();
    }
    outfile.open("newabc.txt",______);//(2)
    if(!outfile) {
        cout<<"Can’t open the file."<<endl;
        abort();
    }
    char buf[80];
    int i=1;
    while(____________) // (3)
    {
        infile.____________; // (4)
        outfile<<________<<": "<<buf<<endl; //(5)
    }
    infile.close();
    outfile.close();
    return 0;
}

代碼如下

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
    {
    fstream outfile,infile;
    infile.open("abc.txt",ios::in); // (1)
    if(!infile)
        {
        cout<<"Can’t open the file."<<endl;
        abort();
        }
    outfile.open("newabc.txt",ios::out);//(2)
    if(!outfile)
        {
        cout<<"Can’t open the file."<<endl;
        abort();
        }
    char buf[80];
    int i=1;
    while(!infile.eof()) // (3)
        {
        infile.getline(buf,80); // (4)一定要寫成getline而非get 不然會顯示1-80行
        outfile<<i++<<": "<<buf<<endl; //(5)
        }
    infile.close();
    outfile.close();
    return 0;
    }


運行結果





學習心得

infile.getline(buf,80); // (4)一定要寫成getline而非get 不然會顯示1-80行


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章