在比较char与字符串(两个数组)并打印结果时遇到麻烦吗?

时间:2019-11-29 03:03:28

标签: c

作为大学课程的一部分,我正在对编程模块做一个介绍,而我们最近的项目使我很困惑。基本上,用户需要输入一个句子,然后将其翻译成莫尔斯电码。我真的很想将用户输入的文本与莫尔斯电码进行比较。任何帮助将不胜感激,谢谢。

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

int main()
{
    char alphabet[27] = { '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', '\0' };
    char morse[26][5] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
    char string[256];
    printf("Please enter a sentence to be converted to IMC: \n");
    scanf("%s", string);
    string[strlen(string)] = '\0';

    for (int i = 0; i < (int)strlen(string); i++)
    {

            if (strcmp (string, alphabet))
            {
                printf("%s ", *(morse + i));
            }
    }

} 

1 个答案:

答案 0 :(得分:0)

使用fgets阅读您的文章。您确定要比较strcmp(string, alphabet)吗?我认为您的意思是

for (int i = 0; i < strlen(string); i++)
{
    for (int j = 0; j < sizeof(alphabet); j++)
    {
            if (string[i] == alphabet[j])
            {
                printf("%s ", *(morse + j));
            }
    }
}```