代码改变世界

实验六

2019-06-18 22:38  孙乾(小U)  阅读(166)  评论(1编辑  收藏  举报

Part 1验证性实验

运行结果:

 

Part 2 文末添加数据

#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
    ofstream out("C:\\Users\\lenovo\\Desktop\\实验六\\实验六part1\\实验六part1\\3.txt",ios_base::app);
    if (!out)
    {
        cout << "Fail to open." << endl;
        return 1;
    }
    out << endl;
    out << "merge successfully";
    out.close();
    return 0;
}

part 2

运行结果:

 

Part 3 随机抽取

#include<iostream>
#include<fstream>
#include<string>
#include<ctime>
#include<sstream>
#include<windows.h>
using namespace std;
string getdate();
int main()
{
    string filename, newfilename;//f是已存在的名单文件,new是即将存随机抽取的文件
    int n, i;
    
    ofstream out;
    ifstream in;
    
    cout << "输入名单列表文件名:";
    cin >> filename;
    cout << "输入随机抽点人数:";
    cin >> n;
    cout << "随机抽点中···" << endl;

    newfilename = getdate().c_str();//新建文件命名
    
    out.open(newfilename);
    if (!out.is_open())
    {
        cout << "Fail to open." << endl;
        return 1;
    }

    for (i = 1; i <= n; i++)
    {    
        in.open(filename);
        if (!in.is_open())
        {
            cout << "Fail to open." << endl;
            return 1;
         }
        
        srand((unsigned)time(NULL));
        int N = rand() % 84;
        
        string s;
        stringstream ss;
        ss << N;
        ss >> s;
        
        char c;
        int j=1;
        while (in.get(c))
        {
            if (c == '\n')
            {
                j++;
                if (j == N)
                {
                    in.get(c);
                    while (c != '\n')
                    {
                        out << c;
                        in.get(c);
                    }
                    out << endl;
                    break;
                }
            }
            else
                continue;
        }
        in.close();
        Sleep(1000);
    }
    out.close();

    char c;
    ifstream nfile(newfilename);
    while (nfile.get(c))
        cout << c;
    nfile.close();
    return 0;
}
const int SIZE1 = 20;
string getdate()
{
    time_t time_seconds = time(0);    
    struct tm now_time;    
    localtime_s(&now_time, &time_seconds); // 使用了更安全的localtime_s()        
    char date[SIZE1];
    strftime(date, SIZE1, "%Y%m%d", &now_time);        
    return (string(date));
}

 

 

互评地址:

https://www.cnblogs.com/pink-fairy/p/11031372.html

https://www.cnblogs.com/q1831726125/p/11044621.html

https://www.cnblogs.com/mzy-1229/p/11031672.htm