C++作业2-文件流对象

作业要求

  1. 生成随机数据文件 text.txt。
  2. 从文件 text.txt 中读取数据后排序。
  3. 将排序好的数据写入 in.txt 文件。
  4. 解决在主程序文件中加载多个头文件时,命名冲突问题。

解决方案

  1. 用随机生成函数生成数据写入文件流,
  2. 然后再读取文件流,讲数据存入 num[],排序,
  3. 将 num[] 中数据写入新文件,
  4. 不在全局打开 std 命名空间,在调用时使用 std::xxx 等方法。

代码

main.cpp

//
//  main.cpp
//  f-work2
//
//  Created by ZYJ on 2017/3/14.
//  Copyright © 2017年 ZYJ. All rights reserved.
//

#include <iostream>
#include <string>
#include "file.hpp"

int main(int argc, const char * argv[])
{
    int n;
    std::cin >> n;
    int *num = new int[n];

    std::string text = "text.txt";  
    std::string in = "in.txt";

    File f = File(text, n, num);

    f.randDate();
    f.sortDate();

    File f_ = File(in, n, num);

    f_.coutDate();

    return 0;
}

file.hpp

//
//  file.hpp
//  f-work2
//
//  Created by ZYJ on 2017/3/14.
//  Copyright © 2017年 ZYJ. All rights reserved.
//

#ifndef file_hpp
#define file_hpp

#include <stdio.h>
#include <string>
#include <fstream>

class File
{
    std::string fileName;   //  文件名
    int n;                  //  数据量
    int *num;

public:
    File(std::string fileName_, int n_, int *num_) : fileName(fileName_), n(n_), num(num_) {}

    void randDate();                    //  生成随机数据文件 fileName
    void sortDate();                    //  读取文件 fileName 中的随机序列并排序,存入 num
    void coutDate();                    //  将 num 中数据存储到 fileName 文件中

    int random(double st, double ed);   //  生成 st~ed 随机数
};

#endif /* file_hpp */

file.cpp

//
//  file.cpp
//  f-work2
//
//  Created by ZYJ on 2017/3/14.
//  Copyright © 2017年 ZYJ. All rights reserved.
//

#include "file.hpp"
#include <algorithm>
#include <ctime>
#include <cstdlib>

#define S 0
#define T 1000000

//  生成随机数据文件
void File::randDate()
{
    std::fstream fp(fileName, std::ios::out);

    while (!fp)
    {
        fp.open(fileName, std::ios::out);
    }

    srand(unsigned(time(0)));

    int k = n;
    while (k--)
    {
        fp << random(S, T) << '\n';
    }

    fp.close();
}

//  读取数据文件,存入num,并排序
void File::sortDate()
{
    std::fstream fp(fileName, std::ios::in);

    while (!fp)
    {
        fp.open(fileName, std::ios::in);
    }

    int k = 0;
    while (fp >> num[k++]) {}
    std::sort(num, num + n);

    fp.close();
}

//  将 num 中数据存入文件中
void File::coutDate()
{
    std::fstream fp(fileName, std::ios::out);

    while (!fp)
    {
        fp.open(fileName, std::ios::out);
    }

    for (int i = 0; i < n; i++)
    {
        fp << num[i] << '\n';
    }

    fp.close();
}

//  生成随机数,随机数在 st~ed 之内
int File::random(double st, double ed)
{
    return (int)st + (ed - st) * rand() / (RAND_MAX + 1.0);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值