C++ 面向对象作业: I/O对象的应用
来源:互联网 发布:java鱼雷2017款评测 编辑:程序博客网 时间:2024/06/05 09:31
1. 补充完整从text.txt文件读取数据后,再写入in.txt文件。
2. 完成从text.txt文件读取数据后,进行排序,再写入in.txt文件。数据量自行设定。
3. 请解决在主程序文件中加载多个头文件时,命名冲突问题。
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 0;}
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(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 0
- C++ 面向对象作业: I/O对象的应用
- 面向对象的S.O.L.I.D 原则
- 面向对象的S.O.L.I.D 原则
- 面向对象的S.O.L.I.D 原则
- c语言应用面向对象
- 面向对象的 C
- 面向对象S.O.L.I.D原则
- 面向对象设计-S.O.L.I.D原则
- java面向对象 第十章 File I/O
- S.O.L.I.D:面向对象设计的5 大原则
- 面向对象第一次作业
- 面向对象第二次作业
- 面向对象第三次作业
- 面向对象作业
- 面向对象 继承作业
- java I/O:对象的序列化
- C#对象的I/O操作
- coursera作业之面向对象的集合
- 凡事预则立 不预则废
- MySQL游标的简单实践
- java Swing 练习
- 《集体智慧编程》第7章 决策树建模 个人笔记
- 网站后台万能密码/10大常用弱口令
- C++ 面向对象作业: I/O对象的应用
- Hive on Spark系列一:CDH5.5配置支持hive on spark
- [置顶]我的第一个C语言程序 (A+B Problem)(cheney-yang)
- [深度学习]资源汇总
- diskpart 制作windows系统的U盘启动盘
- SQL连载(一)----简介
- install boxes on firefly-ubuntu
- 2017年5月百度机器学习实习面经
- 数据交互 ,内置对象之小型注册