C++ 使用文件按相反顺序打印数值列表

该程序演示了如何从一个文本文件中读取整数列表,然后按照相反的顺序将其写入另一个文件。使用C++标准库中的ifstream和ofstream进行文件操作,数组用于存储读取的整数,确保不超过预设容量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用数组
从一个文件中读取一个整数列表
然后按读取顺序的相反顺序将元素写入另一个文件

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
	const int CAPACITY = 50;
	int numbers[CAPACITY];
	int size=0;
	ifstream inputfile;
	ofstream outputfile;
	//打开输入文件
	inputfile.open("D:\\VS 2019\\input.txt");
	if (!inputfile)
	{
		cout << "Error. Input filr cannot be opened." << endl;
		return 0;
	}
	while (inputfile >> numbers[size] && size <= 50)
	{
		size++;
	}
	inputfile.close();
	//打开输出文件
	outputfile.open("D:\\VS 2019\\output.txt");
	if (!outputfile)
	{
		cout << "Error. Input filr cannot be opened." << endl;
		return 0;
	}
	for (int i = size - 1;i >= 0;i--)
	{
		outputfile << numbers[i] << " ";
	}
	outputfile.close();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值