Notice: Credit for part of the code and special thanks for so kindly providing it goes to 'Ganado.'
TotalTemplate
#include <iostream>
using std::cin;
using std::cout;
#include <type_traits>
using std::conditional;
#include <typeinfo>
using std::is_same;
template <typename T>
using MyType = typename conditional<is_same<T, unsigned char>::value, int, T>::type;
/* **********************************************************
template <class T>
This function lets the user enter a number of values of
different data types. The only value passed to it is the
number of values. A running total is kept while the values
are input, and the total is returned.
********************************************************** */
template <class T>
MyType<T> total(int numels)
{
T value{};
MyType<T> sumTotal{};
for (; numels > 0; numels--)
{
static int count = 1;
cout << "Value #" << count++ << ": ";
cin >> value;
sumTotal += value;
}
return sumTotal;
}
int main()
{
int numels = 0;
cout << "TOTAL TEMPLATE DEMO\n\n";
cout << "This program lets you input any amount of values of\n"
<< "different types of data. For instance int, floating-point\n"
<< "and even characters. Once you finish entering your numbers\n"
<< "or characters, it calculates the total and outputs it.\n\n";
cout << "Please the number of values you wish to input: ";
cin >> numels;
while (numels < 0)
{
cout << "Input Error: Enter a valid value!\n";
cout << "Number of values: ";
cin >> numels;
}
cout << "\nEnter " << numels << " floating-point values\n";
cout << "\nThe total value is " << total<double>(numels) << "\n\n";
cout << "Enter " << numels << " integer values\n";
cout << "\nThe total value is " << total<int>(numels) << "\n\n";
cout << "Enter " << numels << " characters\n";
cout << "\nThe total value is " << total<unsigned char>(numels) << "\n\n";
cout << "Thank you for trying this program! Have a nice day!";
cin.ignore();
cin.get();
return 0;
}
No comments:
Post a Comment