1. 补充完整从text.txt文件读取数据后,再写入in.txt文件。
2. 完成从text.txt文件读取数据后,进行排序,再写入in.txt文件。数据量自行设定。
3. 请解决在主程序文件中加载多个头文件时,命名冲突问题。

解决方案

用随机生成函数生成数据写入文件流,

然后再读取文件流,讲数据存入 num[],排序,

将 num[] 中数据写入新文件,

不在全局打开 std 命名空间,在调用时使用 std::xxx 等方法。

代码

main.cpp

#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 ;
}

file.hpp

#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

#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())); 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 = ; 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 = ; 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);
}

最新文章

  1. 窥探Swift系列博客说明及其Swift版本间更新
  2. 推荐相关学习 &amp; 典型算法、典型特征、典型推荐系统框架
  3. Quartz.net(调度框架) 使用Mysql作为存储
  4. java面试每日一题12
  5. http报文在网络中是明文传输的,所以不安全。HTtp必然来临
  6. 解决npm安装模块时 npm err! registry error parsing json
  7. DOM4J读取XML文件
  8. WebPack实例与前端性能优化
  9. Aliexpress API 测试工具
  10. vue+websocket+express+mongodb实战项目(实时聊天)
  11. Android Api 检查參数状态Api
  12. js 发送http请求
  13. python 数据库mysql、redis及发送邮件
  14. K8S 通过 yaml 文件创建资源
  15. [Day3]Scanner类、Random类、流程控制语句
  16. iOS-静态库,动态库,framework浅析(三)
  17. 【BZOJ3244】【UOJ#122】【NOI2013]树的计数
  18. Spring RedisTemplate操作-HyperLogLog操作(7)
  19. java小技巧-生成重复的字符
  20. poj 3250 Bad Hair Day(栈的运用)

热门文章

  1. 【Oracle】异常信息的加工处理
  2. 分布式_理论_07_ZAB
  3. Codeforces Round #286 (Div. 2)A. Mr. Kitayuta&#39;s Gift(暴力,string的应用)
  4. nginx配置允许指定域名下所有二级域名跨域请求
  5. itunesconnect如何提交被决绝过了的相同版本号
  6. mvc那些事
  7. LeetCode Reverse String II
  8. python实现进程的并发
  9. 使用bat文件实现批量重命名功能
  10. BZOJ4066:简单题