我有这个代码试图将莫尔斯代码翻译成字母:
#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)显示morseLetter
1:morseLetter = 0x7fffffffe4d0“....”
(gdb)显示莫尔斯[i]
2:莫尔斯[i] =“· - \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000”
因此,当它在莫尔斯找到正确的字符串时,它显示为“····\ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000”,因此比较失败。我不遵循这里的逻辑。我以为C中的字符串是一个带\ 0的数组。为什么这会失败?
由于
答案 0 :(得分:8)
您已使用中间点·
定义了字母代码,但要解码的文字使用常规点.
strcmp
函数会认为这些字符不同,因为它们是不同的字符。