1

我有这个代码试图将莫尔斯电码翻译成字母:

#include <stdio.h>
#include <string.h>

#define BSIZE 15

char *morseToLetter(char *);


int main() {
    char *morseCode = ".... . .-.. .-.. --- / -.. .- .. .-.. -.-- / .--. .-. --- --. .-. .- -- -- . .-. / --. --- --- -.. / .-.. ..- -.-. -.- / --- -. / - .... . / -.-. .... .- .-.. .-.. . -. --. . ... / - --- -.. .- -.--";    
    char buffer[BSIZE] = { 0 };
    int bufferKey = 0;

    for(int i=0,t = strlen(morseCode)+1;i<t;i++) {
        if (morseCode[i] == '/') {
            printf(" ");
        }
        else {
            if (morseCode[i] == ' ') {
                if (strlen(buffer) == 0) {
                    continue;
                }

                printf("%s",morseToLetter(buffer));

                memset(buffer,0,BSIZE);
                bufferKey = 0;
            }
            else {
                buffer[bufferKey++] = morseCode[i];
            }            
        }        
    }

    if (strlen(buffer) > 0) {      
        printf("%s",morseToLetter(buffer));                
    }

    printf("\n");

    return 0;
}

char *morseToLetter(char *morseLetter) {
    static char morse[][BSIZE] = {
        "·–","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"
    };
    static int morseTotal = sizeof(morse)/sizeof(morse[0]);

    for (int i = 0;i<morseTotal;i +=2) {        
        if (strcmp(morseLetter,morse[i]) == 0) {
            return morse[i+1];
        }
    }

    return '\0';
}

我遇到的问题是 strcmp(morseLetter,morse[i])

当我运行 gdb 时,我得到了这个:

if (strcmp(morseLetter,morse[i]) == 0) {

(gdb) 显示莫尔斯字母

1: 莫尔斯字母 = 0x7ffffffffe4d0 "...."

(gdb) 显示莫尔斯[i]

2: 莫尔斯[i] = "·–\000\000\000\000\000\000\000\000\000"

因此,当它到达正确的莫尔斯字符串时,它显示为“····\000\000\000\000\000\000”,因此比较失败。我没有遵循这里的逻辑。我认为 C 中的字符串将是一个带有 \0 的数组。为什么会失败?

谢谢

4

1 回答 1

8

您已使用中间点定义了字母代码,·但要解码的文本使用常规点.

strcmp函数会认为这些字符不同,因为它们是不同的字符。

于 2013-09-17T22:29:40.990 回答