I'm attempting to use a specialized function to search an array of c strings for the longest (or first tied for longest) member. Right now, I'm getting line 87 error: invalid conversion from `char' to `const char*'|
on my comparison statement. If I switch the templates' inputs to const, I seem to be unable to get my templates' return functions to work. Where am I going wrong?
#include <iostream>
#include <cstring>
using namespace std;
const int numInts = 6;
const int numDubs = 4;
const int numStrs = 5;
const int maxLength = 80;
template <typename T>
T * maxn(T * a, const int n);
template <> char * maxn<char>(char * a, const int n);
int main()
{
cout << "Enter " << numInts << " integers, please.\n";
int ints[numInts];
for (int i = 0; i < numInts; i++)
{
cout << "Int " << i+1 << ":";
while(!(cin >> ints[i]))
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Integers only, please.\n";
cout << "Int " << i+1 << ":";
}
}
cout << "The largest of those is " << *maxn(ints, numInts) << ".\n\n";
cin.clear();
cin.ignore(1000, '\n');
cout << "Enter " << numDubs << " doubles, please.\n";
double dubs[numDubs];
for (int i = 0; i < numDubs; i++)
{
cout << "Double " << i+1 << ":";
while(!(cin >> dubs[i]))
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Doubles only, please.\n";
cout << "Double " << i+1 << ":";
}
}
cout << "The largest of those is " << *maxn(dubs, numDubs) << ".\n\n";
cin.clear();
cin.ignore(1000, '\n');
cout << "Enter " << numStrs << " strings, please.\n";
char strs[numStrs][maxLength];
for (int i = 0; i < numStrs; i++)
{
cout << "String " << i+1 << ":";
while(!(cin.getline(strs[i], maxLength)))
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Something didn't fit. Try again.\n";
cout << "String " << i+1 << ":";
}
}
cout << "The largest of those is " << *maxn(strs, numStrs) << ".\n\n";
return 0;
}
template <typename T>
T * maxn(T * a, const int n)
{
int longest = 0;
for (int i = 1; i < n; i++)
{
if (a[i] > a[longest])
longest = i;
}
return &a[longest];
}
template <> char * maxn<char>(char * a, const int n)
{
int longest = 0;
for (int i = 1; i < n; i++)
{
if(std::strlen(a[i]) > std::strlen(a[longest]))
longest = i;
}
return &a[longest];
}