Write a program writeOddEven.cpp which reads in a list of integers from the term
ID: 3533789 • Letter: W
Question
Write a program writeOddEven.cpp 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 will 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
Explanation / Answer
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string oddfilename, evenfilename;
ofstream oddfile, evenfile;
vector<int> list;
cout<<"Enter the name of the file for odd integers"<<endl;
cin>>oddfilename;
cout<<"Enter the name of the file for even integers"<<endl;
cin>>evenfilename;
cout<<"Enter the integers (even and odd), end by 0"<<endl;
int n, ecount=0, ocount=0;
while(1) {
cin>>n;
if(n==0)
break;
list.push_back(n);
}
oddfile.open(oddfilename.c_str());
evenfile.open(evenfilename.c_str());
for (int i=0; i < list.size(); i++) {
n = list.at(i);
if( n% 2 == 0) {
evenfile<<n << " ";
ecount++;
}
else {
oddfile<<n << " ";
ocount++;
}
}
oddfile.close();
evenfile.close();
cout<<"No. of elements in " <<oddfilename<<" is " << ocount<<endl;
cout<<"No. of elements in " <<evenfilename<<" is " << ecount;
return 0;
}
output:
Enter the name of the file for odd integers
oddfile
Enter the name of the file for even integers
evenfile
Enter the integers (even and odd), end by 0
2
5
7
8
9
3
4
-5
-2
0
No. of elements in oddfile is 5
No. of elements in evenfile is 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.