VS2017C++读取txt文本文档并按奇偶顺序分别保存到新的文档

主要功能是读取一个txt文件,将其中奇数行和偶数行单独输出到新的txt文档。
代码如下:

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

int main()
{
	ifstream txtfile;//打开读取的文件
	ofstream txt01;//保存的文件
	ofstream txt02;//保存的文件
	string temp;
	int index = 0;//用于判断奇偶

	txtfile.open("0.txt", ios::in);
 
	while (!txtfile.eof())            // 若未到文件结束一直循环
	{

		getline(txtfile, temp);//一行一行读取
		if (index%2==0)//判断除以2的余数,即为奇偶的判断
		{
			txt01.open("1.txt", ios::app);
			txt01 << temp;
			txt01 << endl;
			txt01.close();
		}
		else
		{
			txt02.open("2.txt", ios::app);
			txt02 << temp;
			txt02 << endl;
			txt02.close();
		}
		index++;
	}
	txtfile.close();   //关闭文件
	txtfile.close();
	txt01.close();
	txt02.close();
	
	return 0;
}

  • 18
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值