字符串比较不在C中工作

1 c string strcmp

我在我的程序中的函数是应该采取莫尔斯电码输入,把它比作一个字符串数组,并从相应的字符串返回一个字母一旦找到匹配的莫尔斯.我终于设法让它在没有崩溃的情况下运行,但现在它不断返回错误的字母.例如...... ---应该返回sos但是我得到了amb.我尝试通过打印出索引号,莫尔斯代码字符串和字母来测试它,所有这些都匹配起来,所以我认为问题在于字符串比较.

这是代码:

void morsetotext(char mor[])
{
     char alpha[]={"abcdefghijklmnopqrstuvwxyz1234567890 "};
     char *morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", 
     "..", ".---","-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", 
     "...", "-", "..-", "...-",".--", "-..-", "-.--", "--.","-----", ".----", 
     "..---", "...--", "....-",".....", "-....", "--...", "---..", "----." "/ "};
     char letter[8];
     char convert[250];
     int con_count=0;
     int let_count=0;
     int count=0;
     int index=0;
     int length=strlen(mor);

     while (count<length)
     {
           for(let_count=0; let_count<8 && mor[count]!=' '; let_count++)
           {
                            letter[let_count]=mor[count];
                            count++;
           }

           letter[let_count+1]='\0';

           index=0;
           while (strcmp (letter, morse[index])!=1)
           {
                 index++;
           }

           count++;

           printf ("%c", alpha[index]);
     } 
     return;
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

编辑:对不起,这是整个功能.

cni*_*tar 5

while (strcmp (letter, morse[index])!=1)
Run Code Online (Sandbox Code Playgroud)

你可能意味着0而不是1.或者只是说while (!strcmp(...)).


JvO*_*JvO 5

将strcmp()与0进行比较,而不是1.该函数仅在完全匹配时返回0.阅读手册!:)

  • @ user1827962:有效的比较永远不会使程序崩溃,所以`letter`是错误的类型,或者你的递增`count`超过`morse`或`alpha`的结尾.请回答我在评论中提出的问题.无论哪种方式,与1进行比较都是错误的,我可以向你保证`strcmp`没有被破坏. (5认同)