-
Notifications
You must be signed in to change notification settings - Fork 0
/
Morse_Coder.h
executable file
·87 lines (72 loc) · 1.82 KB
/
Morse_Coder.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#pragma once
#include <string>
#include <map>
#include "Morse_tree.h"
#include "String_Tokenizer.h"
#include <fstream>
#include <sstream>
using std::map;
using std::string;
class MorseCoder {
public:
//default constructor
MorseCoder() {}
//encode function
std::string encode(const std::string& letters);
//builds the morse tree
MorseTree<string> build(const std::string& source_name);
private:
//morse tree
MorseTree<string> tree;
//map used for encoding (letter, code)
map<string, string> MorseMap;
//string to hold data from file
string source_name;
};
MorseTree<string> MorseCoder::build(const string& source_name) {
tree.root = new BTNode<string>("");
this->source_name = source_name;
std::ifstream in(source_name.c_str());
if (in) {
string line;
//read each line of the file
while (getline(in, line)) {
//get the letter from position 1
string letter = line.substr(0, 1);
//get the code from the rest of the line
string code = line.substr(1);
//insert
MorseMap.insert({ letter, code });
tree.insert(letter, code);
}
}
return tree;
}
string MorseCoder::encode(const std::string& letters) {
//split line by space if there more than one word
string_tokenizer tokens(letters, " ");
string result;
//while there are more words
while (tokens.has_more_tokens()) {
//store the next word in a temp string
string temp = tokens.next_token();
//split the word by letters
std::istringstream strm(temp);
char next_char;
while (strm >> next_char) {
//reformat the char
string letter;
letter += next_char;
//if the char is a valid letter
if (MorseMap.find(letter) != MorseMap.end()) {
//append its code and a space to result
result += MorseMap[letter];
result += " ";
}
else {
throw Syntax_Error("Invalid Character Encountered");
}
}
}
return result;
}