Write a program which reads in a list of integers from the terminal and writes t
ID: 3533691 • Letter: W
Question
Write a program which reads in a list of integers from the terminal and writes the odd numbers to one file and the even numbers to another file. The program prompts and reads in the name of the file which contain the odd integers, the name of the file to contain the even integers and a list of integers terminated by a 0. In each of the files, exactly five integers should be written on each line except for the last line. In addition to writing the two files, the program writes to the terminal the number of integers in each file.
A sample run of the program would look like this:
> writeOddEven.exe
Enter name of file for odd integers: odd.txt
Enter name of file for even integers: even.txt
Enter list of odd and even integers (followed by 0):
2 3 20 300 400 5 -70 9 9 -101 6 8 10 77 55 400 16 20 300 0
File odd.txt contains 7 odd integers.
File even.txt contains 12 even integers.
After running this program file odd.txt contains:
3 5 9 9 -101
77 55
To view the contents of the file, type "more odd.txt".
After running this program file even.txt contains:
2 20 300 400 -70
6 8 10 400 16
20 300
To view the contents of the file, type "more even.txt". Note that duplicate integers are permitted in the input and in files odd.txt and even.txt. Also note that the names for the files can be different than what is used here (do not hard code these in your solution).
1. Prompt and read in the name of the output for the odd integers. Read and store this name as a
string. Include the C++ command
Explanation / Answer
#include<iostream.h>
#include<fstream.h>
void main()
{
fstream file,file1.file2;
file.open("integer.txt",ios::in);
file1.open("odd.txt",ios::write);
file2.open("even.txt",ios:read);
int n,i=0,j=0;
char ch='endl';
while(file!=eof)
{
n=file.read((*ch)&n,sizeof(n));
if(n%2==0)
{
if(i==5)
{
file2.write((*ch)&ch,sizeof(ch));
file2.write((*ch)&n,sizeof(n));
}
else
file2.write((*ch)&n,sizeof(n));
i++;
if(i>5)
i=0;
}
else
{
if(j==5)
{
file1.write((*ch)&ch,sizeof(ch));
file1.write((*ch)&n,sizeof(n));
}
else
file1.write((*ch)&n,sizeof(n));
}
}
j++;
if(j>5)
j=0;
}
\display even file
while(file2!=eof)
{
n=file2.read((*ch)&n,sizeof(n));
cout<<n<<" ";
}
\display odd file
while(file1!=eof)
{
n=file1.read((*ch)&n,sizeof(n));
cout<<n<<" ";
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.