该程序的主要思想是将文本编码为莫尔斯码并将莫尔斯码解码为文本。
但是程序坏了,我不知道为什么当我写两个单词之间的空格时程序不起作用,而且我的代码和解码也有这个问题。
void encode_out(const char *s){
for(;;++s){
char ch = *s;
if(ch == '\0')
break;
if(isalpha(ch)){
ch = toupper(ch);
fputs(table[ALPHA][ch - 'A'], stdout);//`-'A'` depend on the sequence of character code
} else if(isdigit(ch))
fputs(table[NUM][ch - '0'], stdout);
else if(ch == ' ')
fputc('/', stdout);//need rest space skip ?
else
;//invalid character => ignore
fputc(' ', stdout);
}
fputc('\n', stdout);
}
static void decode_out_aux(MTree *tree, const char *s){
if(tree == NULL) return;
if(*s == '\0')
fputc(tree->value, stdout);
else if(*s == '/')
fputc(' ', stdout);
else if(*s == '.')
decode_out_aux(tree->dot, ++s);
else if(*s == '-')
decode_out_aux(tree->bar, ++s);
}
void decode_out(const char *s){
char *p;
while(*s){
p = strchr(s, ' ');
if(p){
if(p-s != 0){
char code[p-s+1];
memcpy(code, s, p-s);
code[p-s]='\0';
decode_out_aux(root, code);
}
s = p + 1;
} else {
decode_out_aux(root, s);
break;
}
}
fputc('\n', stdout);
}
static void insert_aux(MTree **tree, char ch, const char *s){
if(*tree == NULL)
*tree = calloc(1, sizeof(**tree));
if(*s == '\0')
(*tree)->value = ch;
else if(*s == '.')
insert_aux(&(*tree)->dot, ch, ++s);
else if(*s == '-')
insert_aux(&(*tree)->bar, ch, ++s);
}
static inline void insert(char ch, const char *s){
if(*s == '.')
insert_aux(&root->dot, ch, ++s);
else if(*s == '-')
insert_aux(&root->bar, ch, ++s);
}
void make_tree(void){
root = calloc(1, sizeof(*root));
//root->value = '/';//anything
int i;
for(i = 0; i < 26; ++i)
insert('A'+i, table[ALPHA][i]);
for(i = 0; i < 10; ++i)
insert('0'+i, table[NUM][i]);
}
static void drop_tree_aux(MTree *root){
if(root){
drop_tree_aux(root->dot);
drop_tree_aux(root->bar);
free(root);
}
}
void drop_tree(void){
drop_tree_aux(root);
}
最佳答案
可能还有一些其他问题,但至少你需要解决这个问题:
void encode_out(const char *s)
在这个函数中,s
是一个入参,看起来肯定是你在修改它的内容,所以s
不能有const
修饰符.将其更改为:
void encode_out(char *s)
在你的程序中寻找其他有类似问题的函数,例如decode_out
关于用c语言将文本编码成莫尔斯码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40326028/