Started learning C++ a few days ago, and this is my first full program. It takes in words until an end-of-file character prompt is given, and then outputs which of those words are palindromes and the longest palindrome of those words.
I want to know if my evaluation for whether each string is a palindrome is acceptable given the little knowledge I have about C++ thus far, and by acceptable I mean like not costly or just not agreeable for good C++ code. I was unsure if it would be better to access characters by position in each string with like a "double iterator" to check if they were the same while the iterators converged, or if just making a reversed string and checking is a better approach like I did.
Also just if my general program structure looks okay - I'm rather unsure if my desire to have void functions to clean up my main function is really a good thing to do or otherwise.
Any other critiques would be greatly appreciated :)
#include <iostream>
#include <list>
#include <iomanip>
using std::cin; using std::cout; using std::string;
using std::istream; using std::list; using std::endl;
using std::setw;
istream& read(istream& is, list<string>& word_list)
{
word_list.clear();
string word;
while(is >> word)
word_list.push_back(word);
is.clear();
return is;
}
void evaluate(list<string>& words, string& longest)
{
longest.clear();
typedef string::size_type str_sz;
list<string>::iterator it = words.begin();
while (it != words.end())
{
if (*it == string(it->rbegin(), it->rend()))
{
longest = max(longest, *it);
++it;
}
else
{
it = words.erase(it);
}
}
}
void output(const list<string>& palindrs, const string& longest)
{
if (palindrs.empty())
cout << "No palindromes were given :(" << endl;
else{
cout << "The palindrome(s) given are: " << '\n' << endl;
for (list<string>::const_iterator it = palindrs.begin();
it != palindrs.end(); ++it)
cout << setw(5) << "- \"" << *it << "\"" << endl;
cout << '\n' << "And the longest palindrome is \"" <<
longest << "\"!";
}
}
int main()
{
list<string> words;
cout << "Please enter some words." << endl;
read(cin, words);
string longest;
evaluate(words, longest);
output(words, longest);
return 0;
}