用c语言将文本编码成莫尔斯码

标签 c

该程序的主要思想是将文本编码为莫尔斯码并将莫尔斯码解码为文本。

但是程序坏了,我不知道为什么当我写两个单词之间的空格时程序不起作用,而且我的代码和解码也有这个问题。

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/

相关文章:

C Valgrind 条件跳转或移动

c - 使用栈将中缀表达式转换为前缀时,如果被扫描的和栈顶运算符的优先级相同,应该怎么办?

可以从编译时未知的其他地方修改 const 变量吗

c - 在 ANSI C 中不引入额外变量的情况下根据原始值测试赋值结果

c - 在 Linux 中用 C 语言获取主音量

c - 在递归函数中使用 while

c - 随机打乱一组字符串

c - 在 C 中,我无法将字符串数组的单个元素复制到另一个字符串

c - gdb -- 没有名为 <something> 的源文件 - 英特尔编译器

c - typedef void(* something)(someclass* something) - 这是什么意思?从未见过这样的 typedef 用法