[英]How to translate Morse Code to English in C++?
我目前正在尝试找到一种方法来创建 function 以将摩尔斯电码翻译成英语。 这是我的代码(注意:不是完整的代码)
int main()
{
string const morseCode[] = {".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-",
".....", "-....", "--...", "---..", "----.", "-----", " ", " "};
string const englishLetter[] = {"A", "B", "C", "D", "E", "F",
"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "", " "};
}
string convertToEnglish(string morse, string const morseCode[], string const alpha[])
{
string output;
string compile;
string currentCodeLetter;
int totalMorseCode=38;
string str = morse;
for(int position=0; position<str.size(); ++position) //tried to do the same as englishtomorse but i guess it need a little fix
{
currentCodeLetter = str[position];
for(int marker=0; marker<totalMorseCode; marker++)
{
if(currentCodeLetter==morseCode[marker])
{
compile = alpha[marker];
}
}
output += compile + " ";
}
return output;
}
字符串morse
是来自用户的输入。 给用户的指令是在莫尔斯电码字母之间留一个空格,在莫尔斯电码字之间留三个空格。
问题是,当我输入例如".-"
时,它在文本中应该是A
,output 将是E
和T
,它们是"."
和"-"
。
如何区分摩尔斯电码,因为它们只使用"-"
和"."
? 请不要建议我使用std::map
因为我还没有在我的 class 中了解到,或者可能永远不会,或者任何不寻常的 header 文件。 我只剩下 5 天时间来提交代码。
您在这里所做的是您没有使用“”作为分隔符将代码拆分为字母。 试试这个,
string convertToEnglish(string morse, string const morseCode[], string const alpha[])
{
string output;
string compile;
string currentCodeLetter;
int totalMorseCode=38;
string str = morse;
istringstream iss(str); // This is kinda a hack.
while ( getline( iss, currentCodeLetter, ' ' ) )
{
for(int marker=0;marker<totalMorseCode;marker++)
if(currentCodeLetter==morseCode[marker])
compile = alpha[marker];
output += compile + " ";
compile = "";
}
return output;
}
要获得更优化的解决方案,只需谷歌如何通过“”拆分字符串,StackOverflow 已经得到了您的支持:)。
string convertToEnglish(string morse, string const morseCode[], string const alpha[])
{
string output;
string compile;
string currentCodeLetter;
int totalMorseCode=38;
string str = morse;
String prev;
istringstream iss(str); // This is kinda a hack.
while ( getline( iss, currentCodeLetter, ' ' ) )
{
for(int marker=0;marker<totalMorseCode;marker++)
if(currentCodeLetter==morseCode[marker])
compile = alpha[marker];
if( currentCodeLetter == " " && prev == " " )
{ // Detecteded 3 spaces do your thing here }
prev = currentCodeLetter;
output += compile + " ";
compile = "";
}
return output;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.