实验六 流类库与I/O

一、实验内容

1、 合并两个文件到新文件中。文件名均从键盘输入

2、使用文件I/O流,以文本方式打开Part1中合并后的文件,在文件最后一行添加字符"merge successfully. "

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

int main() {
    ofstream fout;
    string filename;

    cout << "输入要添加的文件名: " ;
    cin >> filename;
    
    fout.open(filename,ios_base::app); 
    if(!fout.is_open()) {  
        cerr << "fail to open file " << filename << endl;
        system("pause");
        exit(0);    
    }
    
    fout << endl; 
    fout<<"merge successfully."<<endl;
    
    fout.close();
    
    return 0;
}
ex2.cpp

效果如下:

3、已知名单列表文件list.txt。编写一个应用程序,实现从名单中随机抽点n位同学(n由键盘输入),在屏幕上显 示结果,同时也将结果写入文本文件,文件名自动读取当天系统日期,如20190611.txt。

#include <iostream>
#include <fstream>   
#include <string>
#include <cstdlib>
#include <ctime>
#include "utils.h"
using namespace std;

int main(){
    string filename, newfilename,str;
    ifstream fin;
    ofstream fout;
    int n; 
    
    cout << "输入名单列表文件名: " ;
    cin >> filename;
    cout << "输入随机抽点人数: " ;
    cin>>n; 
    
    newfilename=getCurrentDate()+".txt";
    
    fin.open(filename);
    if(!fin.is_open()) {
        cerr << "fail to open file " << filename << endl;
        system("pause");
        exit(0);    
    }
    
    fout.open(newfilename);    
    if(!fout.is_open()) {  
        cerr << "fail to open file " << newfilename << endl;
        system("pause");
        exit(0);
    }
    srand(time(0));
    while(n--){
        int m=rand()%83+1,i=0;
        fin.seekg(0); 
        while(getline(fin,str)&&i<m-1){
            i++;
        }
        cout<<str<<endl;
        fout<<str<<endl;
    }
    
    fin.close(); 
    fout.close();
    
    return 0;
}
ex3.cpp

效果如下:

4、编程统计英文文本文件中字符数(包括空格)、单词数、行数。文件名由键盘输入

#include <iostream>
#include <fstream>   
#include <string>
#include <cstdlib>
using namespace std;

int main(){
    string filename;
    ifstream fin;        // 输入文件流对象
    
    cout << "输入要统计的英文文本的文件名: " ;
    cin >> filename;
    
     fin.open(filename);  // 将输入文件流对象fin与文件filename1建立关联 
    if(!fin.is_open()) {  // 如果打开文件失败,则输出错误提示信息并退出 
        cerr << "fail to open file " << filename<< endl;
        system("pause");
        exit(0);
    }
        
    char ch;
    string str;
    int cha=0,word=1,line=1;
    
    while(fin.get(ch)){
        if(ch!='\n')
            cha++;
        if(ch==' '||ch=='\n') 
            word++;
        if(ch=='\n')
            line++;        
    }
    
    cout<<"字符数:"<<cha<<endl; 
    cout<<"单词数:"<<word<<endl;
    cout<<"行数:"<<line<<endl;
    return 0;
}
ex4.cpp

效果如下:

二、实验反思

  • 程序还存在很多不足之处,不具有普遍性和实用性
  • 大部分还是套模板

三、实验小评

  1. https://www.cnblogs.com/xuexinyu/p/11040108.html#4282005
  2. https://www.cnblogs.com/wyy0204/p/11041433.html#4282003
  3. https://www.cnblogs.com/wmy0621/p/11040382.html#4281994

猜你喜欢

转载自www.cnblogs.com/zuiyankh/p/11042897.html