Question

5) Total Template, In C++ please Write a template for a function called total. The function...

5) Total Template, In C++ please

Write a template for a function called total. The function should keep a running total of values entered by the user, then return the total. The argument sent into the function should be the number of values the function is to read. Test the template in a simple driver program that sends values of various types as arguments and displays the results.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>
#include <string>
using namespace std;

template <typename T>
T total(int n) {
    T sum = T(), item;
    for (int i = 0; i < n; ++i) {
        cin >> item;
        sum = sum + item;
    }
    return sum;
}

int main() {
    cout << "Enter 3 doubles: ";
    cout << "Total is " << total<double>(3) << endl;
    cout << "Enter 4 integers: ";
    cout << "Total is " << total<int>(4) << endl;
    cout << "Enter 2 strings: ";
    cout << "Total is " << total<string>(2) << endl;
    return 0;
}
Add a comment
Know the answer?
Add Answer to:
5) Total Template, In C++ please Write a template for a function called total. The function...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT