fix: improve decode validation and warn on unknown Morse token

This commit is contained in:
2025-12-11 14:34:01 +01:00
parent 050bd619f8
commit ae824bd156

View File

@@ -1,6 +1,8 @@
#include <cctype> #include <cctype>
#include <iostream> #include <iostream>
#include <map> #include <map>
#include <optional>
#include <sstream>
#include <string> #include <string>
using namespace std; using namespace std;
@@ -55,10 +57,12 @@ private:
} }
public: public:
char decode(const string &morse) { optional<char> decode(const string &morse) const {
const auto &morse_to_char = get_morse_to_char(); const auto &morse_to_char = get_morse_to_char();
auto it = morse_to_char.find(morse); 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,56 +127,41 @@ void decode_mode() {
if (tolower(input[0]) == 'e') if (tolower(input[0]) == 'e')
return; 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 decoded_message;
string current_morse; bool has_invalid_tokens = false;
bool needs_word_separator = false; bool has_unknown_codes = false;
bool has_invalid_chars = false;
bool in_separator = false;
auto decode_and_add = [&]() { istringstream stream(input);
char decoded = decoder.decode(current_morse); string token;
cout << current_morse << " -> " << decoded << "\n"; while (stream >> token) {
decoded_message += decoded; if (token == "/") {
current_morse.clear(); if (!decoded_message.empty() && decoded_message.back() != ' ')
};
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 += ' '; decoded_message += ' ';
needs_word_separator = false; continue;
}
in_separator = false;
}
current_morse += c;
} else {
in_separator = false;
has_invalid_chars = true;
}
} }
if (!current_morse.empty()) if (token.find_first_not_of(".-") != string::npos) {
decode_and_add(); has_invalid_tokens = true;
cout << token << " -> [ignored: invalid characters]\n";
if (has_invalid_chars) { continue;
cout << "\nWarning: Invalid characters were ignored.\n";
} }
optional<char> decoded = decoder.decode(token);
if (!decoded) {
has_unknown_codes = true;
cout << token << " -> [unknown]\n";
continue;
}
cout << token << " -> " << *decoded << "\n";
decoded_message += *decoded;
}
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"; cout << "\nFinal message: " << decoded_message << "\n\n";
} }
} }