m0_53238525 2021-06-25 20:11 采纳率: 40%
浏览 41
已采纳

ASCII文件输入输出流读写

文件部分实验:学会ASCII文件的基本输入输出流读写(50分)
 (1)写一个程序实现:随机生成两批数据,每批10个整数,范围自定。将第一组数据随机数写入 data1.txt;第二组随机书写入data2.txt (25分)
 (2)写一个程序实现:读取data1.txt和data2.txt的共20个整数有序插入到数组a,再将数组a的结果输出到屏幕同时写入文件data3.txt存档。 (25分)
实验解答:
❶黏贴(1)的实现代码:


❷黏贴(2)的实现代码:

  • 写回答

1条回答 默认 最新

  • 暖晴的天 2021-06-25 20:36
    关注

    其中文件都生成在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;
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器