C+ + Vectors, Iterators: Reading from 2 input files then writing sum to the outp
ID: 3853767 • Letter: C
Question
C+ + Vectors, Iterators: Reading from 2 input files then writing sum to the output file Two input files (.dat) contain integers Inputa.dat Inputb.dat In your main function: a. define a vector for "Inputa.dat & Inputb.dat" b. read the number using "ifstream loop" c. store in the vector one by one. Add the contents of the two vectors and store SUM in the third vector. it is not known which file is shorter so since one file is shorter, neglect the extra terms in the logger file. In a separate loop, write the contents of the vector in an output text file. Use an ITERATOR to access the values. Use an ITERATOR to write to the output file: output.datExplanation / Answer
#include <iostream>
#include <fstream>
#include <vector>
int main()
{
ifstream inputFile1("inputa.dat");
ifstream inputFile2("inputa.dat");
ofstream outputFile("output.dat");
int v1,v2,s,sum;
vector<int> vector1, vector2,vector3;
vector<int>::iterator it;
if (inputFile1) {
// read the elements in the file into a vector
while ( inputFile1 >> v1 )
{
vector1.push_back(v1);
//cout <<v1<<endl;
}
}
if (inputFile2) {
// read the elements in the file into a vector
while ( inputFile2 >> v1 )
{
vector2.push_back(v1);
}
// get size of smaller vector
if(vector1.size() < vector2.size())
s=vector1.size();
else s=vector2.size();
for(int i=0;i<s;i++)
{
// add each element and put in vector 3
sum= vector1[i]+ vector2[i];
vector3.push_back(sum);
}
// Create iterator to access values in vector3
for (it = vector3.begin(); it != vector3.end(); ++it)
{
//cout << *it<< endl ;
outputFile << *it<<endl;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.