....
This is a discussion on Exercise 5.10 (ACCELERATED C++) within the C++ Programming forums, part of the General Programming Boards category; .......
....
Last edited by pantera; 05-10-2010 at 06:33 AM.
Hi, I don't know how to stop the message "The longest palidrome is" from appearing if the user doesn't enter anything (just entering EOF). Where should I put that phrase? I'm not sure enough about the meaning of try-catch stuff. Thanks a lot...
Code:/* Write a program to (1) find all the palindromes in a dictionary and (2) find the longest palindrome */ #include <iostream> #include <string> #include <vector> #include <stdexcept> #include <algorithm> using namespace std; vector<string> read_words(string&); bool found(const string&); int main() { cout << "Enter some words: " << endl; string s; try { vector<string> myvec = read_words(s); vector<string>::iterator it = myvec.begin(); while (it != myvec.end()) { if (found(*it)) { cout << *it << " "; ++it; } else { it = myvec.erase(it); } } cout << endl; cout << "The longest palidrome is "; string::size_type maxlen = 0; string longest; for (int i = 0; i != myvec.size(); ++i) { if (myvec[i].size() > maxlen) { maxlen = max(maxlen, myvec[i].size()); longest = myvec[i]; } } cout << longest << endl; } catch (domain_error e) { e.what(); } return 0; } vector<string> read_words(string& s) { vector<string> v; while (cin >> s) v.push_back(s); typedef vector<string>::size_type vec_sz; vec_sz size = v.size(); if (size == 0) throw domain_error("Empty vector"); return v; } bool found(const string& s) { bool found = true; for (string::const_iterator i = s.begin(), j = s.end() - 1; i < j; ++i, --j) { if (*i != *j) found = false; } return found; }
If the user enters no text, but an immediate EOF, the line "The longest palindrome is: " is not printed. If you change your catch to be
then you'll see "Empty vector" printed instead.Code:cout << e.what();