From ae824bd156d6cb85e77b45e7501e70776d18d043 Mon Sep 17 00:00:00 2001 From: Kharec Date: Thu, 11 Dec 2025 14:34:01 +0100 Subject: [PATCH] fix: improve decode validation and warn on unknown Morse token --- main.cpp | 81 ++++++++++++++++++++++++-------------------------------- 1 file changed, 35 insertions(+), 46 deletions(-) diff --git a/main.cpp b/main.cpp index f04284b..2e702e2 100644 --- a/main.cpp +++ b/main.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include using namespace std; @@ -55,10 +57,12 @@ private: } public: - char decode(const string &morse) { + optional decode(const string &morse) const { const auto &morse_to_char = get_morse_to_char(); auto it = morse_to_char.find(morse); - return it != morse_to_char.end() ? it->second : '?'; + if (it == morse_to_char.end()) + return nullopt; + return it->second; } }; @@ -123,55 +127,40 @@ void decode_mode() { if (tolower(input[0]) == 'e') return; - size_t start = input.find_first_not_of(" \t"); - if (start == string::npos) - continue; - size_t end = input.find_last_not_of(" \t"); - string decoded_message; - string current_morse; - bool needs_word_separator = false; - bool has_invalid_chars = false; - bool in_separator = false; + bool has_invalid_tokens = false; + bool has_unknown_codes = false; - auto decode_and_add = [&]() { - char decoded = decoder.decode(current_morse); - cout << current_morse << " -> " << decoded << "\n"; - decoded_message += decoded; - current_morse.clear(); - }; - - for (size_t i = start; i <= end; ++i) { - char c = input[i]; - - if (c == ' ' || c == '/') { - if (!in_separator && !current_morse.empty()) { - decode_and_add(); - in_separator = true; - } - if (c == '/') - needs_word_separator = true; - } else if (c == '.' || c == '-') { - if (in_separator) { - if (needs_word_separator && !decoded_message.empty()) { - decoded_message += ' '; - needs_word_separator = false; - } - in_separator = false; - } - current_morse += c; - } else { - in_separator = false; - has_invalid_chars = true; + istringstream stream(input); + string token; + while (stream >> token) { + if (token == "/") { + if (!decoded_message.empty() && decoded_message.back() != ' ') + decoded_message += ' '; + continue; } + + if (token.find_first_not_of(".-") != string::npos) { + has_invalid_tokens = true; + cout << token << " -> [ignored: invalid characters]\n"; + continue; + } + + optional decoded = decoder.decode(token); + if (!decoded) { + has_unknown_codes = true; + cout << token << " -> [unknown]\n"; + continue; + } + + cout << token << " -> " << *decoded << "\n"; + decoded_message += *decoded; } - if (!current_morse.empty()) - decode_and_add(); - - if (has_invalid_chars) { - cout << "\nWarning: Invalid characters were ignored.\n"; - } + if (has_invalid_tokens) + cout << "\nWarning: Tokens with invalid characters were ignored.\n"; + if (has_unknown_codes) + cout << "Warning: Unknown Morse codes were skipped.\n"; cout << "\nFinal message: " << decoded_message << "\n\n"; }