c++ 实验六 流类库与I/O

一、基础练习 合并文件

#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
using namespace std;
int main()
{
    string filename1;
    cin>>filename1;
    ofstream fout;
    ifstream fin;

    fin.open(filename1,ios_base::app);
    if(!fin.is_open())
    {
        cerr<<"fail to open file"<<filename1<<endl;
        system("pause");
        exit(0);
    }
    fout.open(filename1,ios_base::app);
    fout<<"merge successfully."<<endl;

    fin.close();
    fout.close();

    return 0;
}
add

二、应用实践,抽人

因为其他是工具包,所以不贴出来了就

#include <iostream>
#include<fstream>
#include <string>
#include <cstdlib>
#include<stdlib.h>
#include<ctime>
#include "utils.h"

using namespace std;

int main() {

    string filename, oldfile;
    int n;
    ofstream  fout;
    ifstream  fin;
    cout << "filename:  ";
    cin >> oldfile;


    fin.open(oldfile,ios_base::in);
    if (!fin.is_open())
    {
        cerr << "fail to open file" << oldfile << endl;
        system("pause");
        exit(0);
    }
    cout << "number:  ";
    cin >> n;
    srand((unsigned int)(time(0)));

    filename = getCurrentDate();

    fout.open(filename);
    string t, a[90];
    int count = 0;
    if (fin)
    {
        while (getline(fin, t))
        {
            a[count] = t;
            count++;
        }
    }
    for (int i = 0; i < n; i++)
    {
        count = rand() % 83;
        cout << a[count] << endl;
        fout << a[count] << endl;
    }

    fin.close();
    fout.close();
    cout << filename << endl;

    system("pause");

    return 0;
}
main.cpp

三、统计文章中的字符等

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    string file1;
    ifstream fin;
    int letter=0, line=1, words=0,k=0;

    cout << "要统计的文件名:  ";
    cin >> file1;
    fin.open(file1);
    char ch;
    while (fin.get(ch))
    {
        if(ch!='\n')
            letter++;
        if (ch == ' ')
        {
            k = 1;
        }
        if (k == 1 && ch != ' ')
        {
            words++;
            k = 0;                //    防止一个单词多个空格
        }

        

        if (ch == '\n')
        {
            line++;
            words++;
        }
    }
    fin.close();
    cout << "字符数:" << letter << endl << "单词数:" << words+1 << endl << "行数:" << line << endl;
                                                    //+1是因为最后一行没有换行符,会漏掉一个;
    system("pause");
    return 0;
}
main.cpp

四、实验总结

1.写这次实验之前,基本没用过文件的输入输出流,上手用了比较长的时间,然后可能用法还不太严谨,只是得出了正确的结果。

猜你喜欢

转载自www.cnblogs.com/aiwenzhuo/p/11031266.html
今日推荐