#include #include #include #include #include #include const string ALPHABET = "abcdefghijklmnopqrstuvwxyz"; const char *const FORMAT_UNDERSCORE = "\033[4m"; const char *const END_FORMATTING = "\033[0m"; const char *const DICTIONARY_PATH = "./dictionary.txt"; std::string input(const char *message) { if (message != nullptr) std::cout << message; std::cout << FORMAT_UNDERSCORE; std::flush(std::cout); std::string ret; std::getline(std::cin, ret); std::cout << END_FORMATTING; return ret; } std::string fileRead(const std::string &filePath) { std::ifstream file(filePath, std::ios::binary); if (!file.is_open()) throw std::runtime_error("File couldn't be found"); std::string content; const int BUF_LENGTH = 1024; char buf[BUF_LENGTH]; while (file.read(buf, BUF_LENGTH)) content.append(buf, file.gcount()); content.append(buf, file.gcount()); if (!file.eof() && file.fail()) throw std::runtime_error("Error: Failed to read the file '" + filePath + "'"); return content; } std::unordered_set readDictionary() { std::string fileContent = fileRead(DICTIONARY_PATH); std::unordered_set set; size_t last = 0, idx; while ((idx = fileContent.find('\n', last)) != std::string::npos) { std::string sub = fileContent.substr(last, idx - last); set.insert(sub); last = idx + 1; } set.insert(fileContent.substr(last)); return set; } int main() { std::cout << "Welcome to TDDD86 Word Chain.\n" << "If you give me two English words, I will transform the\n" << "first into the second by changing one letter at a time.\n\n" <<"Please type two words: "; std::flush(std::cout); std::unordered_set dictionary = readDictionary(); std::string userInput = input(nullptr); size_t wordSep = userInput.find(' '); std::string wordOne = userInput.substr(0, wordSep); std::string wordTwo = userInput.substr(wordSep + 1); std::cout << "Chain from " << wordTwo << " to " << wordOne << std::endl; std::cout << "Have a nice day!" << std::endl; return 0; }