I have a Morse Code translator, which can translate text to Morse code and vice-versa. Note that for the two files that the first three lines are generated by the Code::Blocks IDE.
translator.h
#ifndef SPLIT_H_INCLUDED
#define SPLIT_H_INCLUDED
#endif // SPLIT_H_INCLUDED
#include <iostream>
#include <map>
#include <string>
#include "split.h"
std::string SPACE (" ");
std::map<char, std::string> charMap;
std::map<std::string, char> morseMap;
bool hasInit = false;
void init()
{
charMap['a'] = ".-";
charMap['b'] = "-...";
charMap['c'] = "-.-.";
charMap['d'] = "-..";
charMap['e'] = ".";
charMap['f'] = "..-.";
charMap['g'] = "--.";
charMap['h'] = "....";
charMap['i'] = "..";
charMap['j'] = ".---";
charMap['k'] = "-.-";
charMap['l'] = ".-..";
charMap['m'] = "--";
charMap['n'] = "-.";
charMap['o'] = "---";
charMap['p'] = ".--.";
charMap['q'] = "--.-";
charMap['r'] = ".-.";
charMap['s'] = "...";
charMap['t'] = "-";
charMap['u'] = "..-";
charMap['v'] = "...-";
charMap['w'] = ".--";
charMap['x'] = "-..-";
charMap['y'] = "-.--";
charMap['z'] = "--..";
charMap['0'] = "-----";
charMap['1'] = ".----";
charMap['2'] = "..---";
charMap['3'] = "...--";
charMap['4'] = "....-";
charMap['5'] = ".....";
charMap['6'] = "-....";
charMap['7'] = "--...";
charMap['8'] = "---..";
charMap['9'] = "----.";
charMap['.'] = ".-.-.-";
charMap[','] = "--..--";
charMap['?'] = "..--..";
charMap[' '] = "/";
for (std::map<char, std::string>::iterator i = charMap.begin(); i != charMap.end(); i++) {
morseMap[i -> second] = i -> first;
}
}
std::string translateToMorse(std::string plainText)
{
if (!hasInit) {
init();
}
std::string result;
for (int i = 0; plainText[i]; i++) {
result.append(charMap[plainText[i]]);
result.append(SPACE);
}
return result;
}
std::string translateFromMorse(std::string morseText)
{
if (!hasInit) {
init();
}
std::string result;
std::vector<std::string> morse = split(morseText, SPACE[0]);
for (std::vector<std::string>::iterator i = morse.begin(); i != morse.end(); i++) {
result.push_back(morseMap[*i]);
}
return result;
}
split.h
#ifndef SPLIT_H_INCLUDED
#define SPLIT_H_INCLUDED
#endif // SPLIT_H_INCLUDED
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
Concerns:
- Are the three generated lines necessary and are they used correctly?
- Is there a way to simplify the code?