/****************************************************************************** * This program that searches a dictionary file to find palindromes. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #include "Utils.hpp" #include #include #include #include #include #include std::locale utf8loc(std::locale(), new std::codecvt_utf8); using namespace std; bool isPalindrome(wstring s) noexcept { wstring s0 = std::regex_replace(s, wregex(L"\\W+"), L""); s0 = Utils::tolower(s0); int const sLen = s0.length(); if (sLen < 4) { return false; } for (int x = 0; x <= (sLen - 1) / 2; ++x) { if ((int)(s0[x]) != (int)(s0[sLen - 1 - x])) { return false; } } return true; } void searchTextFile(wstring filespec) { wifstream ifh(filesystem::path(filespec).c_str()); if (!ifh.good()) { throw ios_base::failure(Utils::wchar_to_UTF8(L"Problem opening input file!")); } ifh.imbue(utf8loc); wstring line; while (getline(ifh, line)) { if (isPalindrome(line)) { wcout << line << endl; } } ifh.close(); } int main(int argc, char **argv) { setlocale(LC_ALL, "en_US.UTF-8"); wcout.imbue(utf8loc); wcin.imbue(utf8loc); if (argc != 2) { wcout << L"Syntax: " << Utils::UTF8_to_wstring(argv[0]) << L" {filename}" << endl; exit(1); } wstring filespec = Utils::UTF8_to_wstring(argv[1]); try { searchTextFile(filespec); } catch (ios_base::failure ex) { wcout << L"Error: " << Utils::exceptionMessage(ex) << endl; } return 0; }