سؤال

I have this code that tries to translate morse code to letters:

#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';
}

The problem I am having is with the strcmp(morseLetter,morse[i])

When I run gdb I get this:

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

(gdb) display morseLetter

1: morseLetter = 0x7fffffffe4d0 "...."

(gdb) display morse[i]

2: morse[i] = "·–\000\000\000\000\000\000\000\000\000"

So when it gets to the correct string in morse it shows up as "····\000\000\000\000\000\000" and so the comparison fails. I am not following the logic here. I thought that a string in C would be an array with a \0. Why is this failing?

Thanks

هل كانت مفيدة؟

المحلول

You have defined the letter codes using the middle dot, · but the text to decode uses the regular dot .

The strcmp function will consider these characters different because they are different characters.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top