Hello Community,
Once again I kindly ask for help. As the topic suggests, this is what I try to achieve: Finding a way to sum character values in a particular way.
Here is my code so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
using std::cin;
using std::cout;
template <class T>
T total(T numels)
{
T number{};
T sumTotal{};
for (; numels > 0; numels--)
{
static int count = 1;
cout << "Enter value #" << count++ << ": ";
cin >> number;
sumTotal += number;
}
return sumTotal;
}
int main()
{
int numels = 0;
cout << "Enter " << numels << " characters\n\n";
cout << "The total value is "
<< total<unsigned char>(numels) << "\n";
cin.ignore();
cin.get();
return 0;
}
|
By the nature of what is passed to the template function, what is returned is a character. If I change the function call the one below, the value of this character is output:
static_cast<unsigned int>(total<unsigned char>(numels) << "\n";
a+b+c = 38 = '&'
Some remarks
I know of course why, after summing a '97', b '98', c '99', the output is & '38' and not 294. It is the range of unsigned char 0 ... n[255]
The reason for passing an <unsigned char> is to have some meaningful values to watch while debugging. Otherwise, what I get is a '97' + b '98' = -61 'À' etc. The output will of course still be 38 = '&'
One solution I tried is:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
if (T number == unsigned char)
{
static_cast<unsigned int>(T number);
}
// Error:
// error C2143: syntax error: missing ',' before '=='
// 1> (46): note: see reference to function template instantiation 'T total<unsigned char>(T)' being compiled
// 1> with
// 1> [
// 1> T=unsigned char
// 1> ]
|
And this:
1 2 3 4
|
if (sumTotal == unsigned char(sumTotal))
{
return static_cast<unsigned int>(sumTotal);
}
|
And this:
|
static_cast<unsigned int>(sumTotal += number);
|
The idea was trying to say: if the type is unsigned char, then make it an unsigned integer and return this and not a character. This did not work. Likely because the way I tried is patently wrong. The other less likely reason is, that no matter what is done inside, what is passed to the template is returned from the template.
Summary/Question
Is there a solution to this problem? Meaning to get across, that, if a + b + c is input, the result is 294, that this should be an integer value, and that this should be returned.
Code ..., I would not normally ask for any, but in this case it would be appreciated if it is inevitable. It must not be a/the solution. The general direction in which to look for, or an explanation and some general way how to go about doing it, would also do!