摩尔斯电码翻译(C++实现)

来源:互联网 发布:苹果mac键盘鼠标失灵 编辑:程序博客网 时间:2024/05/01 04:29
#include <stdio.h>

#include <string.h>

//首先将摩斯电码的36个符号及其电码(1对应.,0对应-)记录在一个数组内

char a[36][6] = { "10","0111","0101","011","1","1101","001","1111","11","1000","010","1011","00","01","000","1001","0010","101","111","0",
"110","1110","100","0110","0100","0011","00000","10000","11000","11100","11110","11111","01111","00111","00011","00001" };
//此函数实现摩斯电码的查找比对功能
void search(char s[6])
{
for (int i = 0; i < 36; i++)
if (strcmp(s, a[i]) == 0)
{
if (i < 26)
putchar(i + 97);
else
putchar(i + 48 - 26);
break;
}
for (int i = 0; i < 6; i++)
s[i] = 0;

}

//这是主要的函数 主要是实现莫尔斯电码的翻译过程

void translate(char *s)
{
char dest[6];
int index = 0;
for (int i = 0; s[i] != '\0'; i++)
{
if (s[i] == ' ' || s[i] == '/')  //待翻译的电码需要以空格和除号分隔开来
  {
dest[index] = '\0';
search(dest);
index = 0;
}
else
{
dest[index++] = s[i];
}
}
dest[index] = 0;
search(dest);
}
int main()
{
printf("Please puts the Morse code or the cleartext:");
char *s;
s = new char[10000];
gets_s(s,10000);

if (s[0] != '.'&&s[0] != '-') { //如果要将正常的字符翻译成摩斯电码,直接输入字符串即可,如果要将摩斯电码翻译成字符串 直接输入摩斯电码即可

//程序有自动识别的功能

for (int i = 0; i < strlen(s); i++)
if (s[i] >= '0' && s[i] <= '9')
printf(a[26 + s[i] - 48]);
else if (s[i] >= 'a'&& s[i] <= 'z')
printf(a[s[i] - 97]);
else if (s[i] >= 'A' && s[i] <= 'Z')
printf(a[s[i] - 65]);
else {
printf("?");
break;
}
}
else {
for (int i = 0; s[i] != '\0'; i++)
if (s[i] == '.')
s[i] = '1';
else if (s[i] == '-')
s[i] = '0';
translate(s);
}
return 0;
}
原创粉丝点击