Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Note: If you have already answered this question, Don\'t answer again. I want to

ID: 3589357 • Letter: N

Question

Note: If you have already answered this question, Don't answer again. I want to see someone else's approach.

Write a C++ program that will read in values and return the sum of different data types.

Write a function

            T accum(vector <T> v)

that forms and returns the "sum" of all items in the vector v passed to it. For example, if T is a numeric type such as int or double, the numeric sum will be returned. If T represents the STL string type, the result of concatenation is returned.

Use input file tempData.txt as input. The first five lines will hold integer values. Sum these values.   The next six lines hold string values.   "Sum" (concatenate) these string values together.   For each type, display the values and their respective sums.  

NOTE: for any type T, the expression T( ) yields the value or object created by the default constructor.   For example, T() yields the empty string object if T is the string class.   If T represents a numeric type such as int, then T() yields 0. You may find this helpful when initializing your accumulator.

Be sure to use good programming methodology and keep your project modular.

the tempData.txt has the following

101
599
245
853
99
Exceptions
are
used
to
signal
errors

Explanation / Answer

#include<iostream>
#include<string>
#include<vector>
#include<fstream>

using namespace std;

template <class T>
T accum(vector<T> v){
   
    T res;
    for (int i = 0; i<v.size(); i++){
        if (i == 0)
           res = v[0];
        else
           res = res + v[i];
    }
    return res;
}


int main(){
   ifstream fin;
   vector<int> a;
   vector<string> c;

   int b;
   string d;
   fin.open("tempData.txt");
   if (!fin){
       cout << "Error opening file ";
       return 0;
   }
   for (int i = 0; i<5; i++){
       fin >>b;
       a.push_back(b);
   }
   cout << accum<int>(a) << endl;
   for (int i = 0; i<5; i++){
       fin >>d;
       c.push_back(d);
   }
   cout << accum<string>(c) << endl;
   fin.close();
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote