/* Write a C++ program to accept '
n' numbers from user through Command Line Argument.Store all Even and Odd
numbers in file "Even.txt" and "Odd.txt" respectively.*/
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
ofstream out;
int a[10]={1,2,3,4,5,6,7,8,9},
b[10];
out.open("input.txt");
out.write((char*) &a, size of
(a));
out.close();
ifstream in;
ofstream fp1, fp2;
in.open("input.txt");
in.read((char*) &b, size of
(b));
fp1.open ("even.txt");
fp2.open("odd.txt");
for (int i=0; i<10; i++)
{
if (b[i]%2==0)
fp1<<b[i]<<"";
else
fp2<<b[i]<<"";
}
in.close();
fp1.close();
fp2.close();
if stream fp;
char ch;
fp.open ("even.txt");
cout<<"the even file
contents are:";
while (fp)
{
fp.get(ch);
cout<<ch;
}
fp.close();
fp.open("odd.txt");
cout<<"the odd file
contents are:";
while (fp)
{
fp.get(ch);
cout<<ch;
}
fp.close();
getch();
}
Another way
#include <iostream>
#include <fstream>
#include <stdlib.h>
#define MAX 10
int main()
{
int num[MAX],n;
cout<<"Enter the
Limit\n";
cin>>n;
cout<<"Enter the
elements\n";
for(int i=0;i<n;i++)
cin>>num[i];
ofstream fout1,fout2;
// creating and opening files
fout1.open("Even.txt");
if(fout1.fail())
{
cout<<"Couldn't open
file:\n Odd.txt";
exit(1);
}
fout2.open("Odd.txt");
if(fout2.fail())
{
cout<<"Couldn't open
file:\n Even.txt";
exit(1);
}
// even and odd
for(int i=0;i<n;i++)
{
if(num[i]%2==0)
fout1<<num[i]<<"
";
else
fout2<<num[i]<<"
";
}
fout1.close();
fout2.close();
ifstream fin1,fin2;
fin1.open("Odd.txt");
if(fin1.fail())
{
cout<<"Couldn't open
file:\n Odd.txt";
exit(1);
}
fin2.open("Even.txt");
if(fin2.fail())
{
cout<<"Couldn't open
file:\n Even.txt";
exit(1);
}
cout<<"Contents of
Odd.txt\n";
do
{
char ch;
fin1.get(ch);
cout<<ch<<"
";
}
while(fin1);
fin1.close();
cout<<"\nContents of
Even.txt\n";
do
{
char ch;
fin2.get(ch);
cout<<ch<<"
";
}
while(fin2);
fin2.close();
cout<<"\n"
system("pause");
return 0;
}