Answer to Question #214034 in C++ for Hemambar

Question #214034

Write a program to create a numeric file and split the file into two files, one containing all odd

numbers and another with even numbers.


1
Expert's answer
2021-07-16T01:05:45-0400
#include <iostream>//Input Output stream library(use consol input and output)
#include <fstream>//File stream (use file input and output)
#include <ctime>;//Use random numbers-by times
using namespace std;
int main()
{
	srand(time(0));//generate random value
	//Create file
	string fname;
	cout << "Enter file name and type(.txt): ";
	cin >> fname;
	int size = 0;//count numbers
	ofstream fout(fname);//Create file for write numbers
	//Create menu
	cout << "Menu\n";
	cout << "\t1 -Create file manually(with console input)\n";
	cout << "\t2 -Create file automatically (with random numbers)\n";
	int cmd;
	cin >> cmd;
	switch (cmd)
	{
	case 1:
	{
		cout << "Enter the count of numbers:";
		cin >> size;
		cout << "Please enter numbers\n";
		for (int i = 0; i < size; i++)
		{
			int x;
			cin >> x;
			fout << x << " ";//write to file
		}
		break;
	}
	case 2:
	{
		cout << "Enter the count of numbers:";
		cin >> size;
		cout << "Wait!!...Fill file with random numbers\n";
		for (int i = 0; i < size; i++)
		{
			int num = rand() % 10000;//[0..10000) 
			fout << num << " ";
		}
		break;
	}
	default:cout << "Error!!! Command not found!\n";
		break;
	}
	fout.close();
	//Split file
	ifstream inp(fname);//Read numbers file
	ofstream odfile("odd.txt");//all odd numbers write to odd.txt file
	ofstream evenfile("even.txt");//all even numbers write to evenfile.txt
	for (int i = 0; i < size; i++)
	{
		int x;
		inp >> x;//read number
		if (x % 2 == 1)//if odd number
			odfile << x << " ";//write to odfile
		else
			evenfile << x << " ";//else write to even file
	}
	//close file handler
	inp.close();
	odfile.close();
	evenfile.close();
	cout << "Done!The file is split in two:";
	//you can view file to application directory
	return 0;
}

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
APPROVED BY CLIENTS