#include <iostream>

using namespace std;

template <typename T>
T total(T numValues)
{

}


int main()
{



	cin.ignore();
	cin.get();

	return 0;
}

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 shuold be the number of values the function is to read. Test the template in a simple driver program.

This problem is easy enough to set up(like I did up top), but I dont exactly get what the function is supposed to do. Do I need to pass it an array or vector that is filled by a user in main using a loop? Then add the elements? How do you guys decipher this text =(

Thanks

Edited 6 Years Ago by clutchkiller: n/a

I interpret it as the function is supposed to perform input as well as calculate the total. So your main would be something like so:

int main()
{
  int n = 10;

  std::cout<< total(n) <<'\n';
}
#include <iostream>

using namespace std;

template <typename T>
T total(T numValues)
{
	T total = 0;

	T value = 0;

	for(int i = 1; i <= numValues; i++)
	{
		cout << "Enter value " << i << ": "; 
		cin >> value;

		total += value;		
		
		cout << endl;
	}

	return total;
}

int main()
{
	int n = 10;


	cout << total(n);

	cin.ignore();
	cin.get();

	return 0;
}

So I have got this so far, but it only works when I enter in whole numbers. If I enter in a char or double, it bombs. Shouldnt it except any data type and tally it to the total variable? Thanks

Edited 6 Years Ago by clutchkiller: n/a

>Shouldnt it except any data type?
Templates aren't magic. When you call total with an int argument, type deduction turns T into int . Once you instantiate the template, you turn T into a single concrete type.

This question has already been answered. Start a new discussion instead.