文件部分实验:学会ASCII文件的基本输入输出流读写(50分)
(1)写一个程序实现:随机生成两批数据,每批10个整数,范围自定。将第一组数据随机数写入 data1.txt;第二组随机书写入data2.txt (25分)
(2)写一个程序实现:读取data1.txt和data2.txt的共20个整数有序插入到数组a,再将数组a的结果输出到屏幕同时写入文件data3.txt存档。 (25分)
实验解答:
❶黏贴(1)的实现代码:
❷黏贴(2)的实现代码:
文件部分实验:学会ASCII文件的基本输入输出流读写(50分)
(1)写一个程序实现:随机生成两批数据,每批10个整数,范围自定。将第一组数据随机数写入 data1.txt;第二组随机书写入data2.txt (25分)
(2)写一个程序实现:读取data1.txt和data2.txt的共20个整数有序插入到数组a,再将数组a的结果输出到屏幕同时写入文件data3.txt存档。 (25分)
实验解答:
❶黏贴(1)的实现代码:
❷黏贴(2)的实现代码:
其中文件都生成在C盘的根目录。
第一问:
#include<iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ofstream myfile1("C:\\data1.txt", ios::trunc);
ofstream myfile2("C:\\data2.txt", ios::trunc);
//ofstream outfile1("C:\\data3.txt", ios::trunc);
int a, b;
printf("请输入随机数范围以空格隔开:");
scanf("%d %d", &a, &b);
for (int i = 0; i < 10; i++)
{
int num = (rand() % (b - a + 1)) + a;
myfile1 << num << endl;
}
for (int i = 0; i < 10; i++)
{
int num = (rand() % (b - a + 1)) + a;
myfile2 << num << endl;
}
myfile1.close();
myfile2.close();
return 0;
}
第二问:
#include<iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream myfile1("C:\\data1.txt");
ifstream myfile2("C:\\data2.txt");
ofstream outfile1("C:\\data3.txt", ios::trunc);
int a[30];
if (!myfile1.is_open())
{
cout << "can not open this file" << endl;
return 0;
}
for (int i = 0; i < 10; i++)
{
myfile1 >> a[i];
}
if (!myfile2.is_open())
{
cout << "can not open this file" << endl;
return 0;
}
int i = 10;
for (; i < 20; i++)
{
myfile2 >> a[i];
}
a[i] = '\0';
for (int i = 0; a[i] != '\0'; i++)
{
cout << a[i] <<endl;
outfile1 << a[i] << endl;
}
myfile1.close();
myfile2.close();
outfile1.close();
return 0;
}