cpp_prac/morse/morse_code.cc

45 lines
965 B
C++
Raw Normal View History

2025-01-12 15:22:13 +01:00
#include "morse_code.h"
Morse_code::Morse_code(std::string filename) {
std::ifstream in(filename);
char c;
while (in >> c) {
std::string s;
in >> s;
morse_map.insert(std::make_pair(c, s)); // gay ass
}
}
std::string Morse_code::encode(const std::string &str) {
std::string res;
for (auto &c : str) {
2025-01-12 15:50:45 +01:00
auto it = morse_map.find(toupper(c)); // convert
2025-01-12 15:22:13 +01:00
if (it != morse_map.end()) {
res += it->second + " ";
}
}
return res;
}
2025-01-12 15:50:45 +01:00
std::string Morse_code::decode(std::string str) {
std::stringstream in(str);
std::string res;
std::string s;
while(in >> s) {
auto it = std::find_if(morse_map.begin(), morse_map.end(), [&](std::pair<char, std::string> &p) {
return p.second == s;
});
2025-01-12 15:22:13 +01:00
2025-01-12 15:50:45 +01:00
if (it != morse_map.end()) {
res += it->first;
} else {
res += '?';
}
}
return res;
}