Answer to Question #283283 in C++ for yash gupta

Question #283283

Write a C++ program using file handling to perform the following operations


(A) A file named “data.txt” contains number from 0 to 100. Open the “data.txt” file in read


mode.


(B) Read data from “data.txt” file.


(C) If the number is odd, open a new file named “odd.txt” and write the odd number into


“odd.txt” file.


(D) If the number is even, open a new file named “even.txt” and write the even number into


“even.txt” file.


(E) Display the data of all files.


1
Expert's answer
2021-12-28T10:03:35-0500
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
	//Fill file data.txt from 1 to 100
	ofstream fout("data.txt");
	if(!fout.is_open())
	{
		cout<<"File is not exist!";
	}
	else
	{
		for(int i=0;i<=100;i++)
		{
			fout<<' '<<i;
		}
	}
	fout.close();
	//Open data.txt for reading anf fill odd.txt and even.txt
	ifstream in("data.txt",ios_base::in);
	ofstream oddOut("odd.txt");
	ofstream evenOut("even.txt");
	int num;
	while(in.good())
	{
		in>>num;
		if(num%2==1)
		{
			oddOut<<' '<<num;	
		}
		else
		{
			evenOut<<' '<<num;	
		}
	}
	in.close();
	oddOut.close();
	evenOut.close();
	cout<<"Content of data.txt:\n";
	ifstream ind("data.txt",ios_base::in);
	while(!ind.eof())
	{
		cout<<(char)ind.get();
	}
	ind.close();
	cout<<"\nContent of odd.txt:\n";
	ifstream inOdd("odd.txt",ios_base::in);
	while(!inOdd.eof())
	{
		cout<<(char)inOdd.get();
	}
	inOdd.close();
	cout<<"\nContent of even.txt:\n";
	ifstream inEven("even.txt",ios_base::in);
	while(!inEven.eof())
	{
		cout<<(char)inEven.get();
	}
	inEven.close();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog