0

I'm making a morse code translator through the command line but am having trouble comparing the array holding user input to the array holding the morse code equivalents.

const char *morse[SIZE] = {
"0 ----- ",
"1 .---- ",
"2 ..--- ",
"3 ...-- ",
"4 ....- ",
"5 ..... ",
"6 -.... ",
"7 --... ",
"8 ---.. ",
"9 ----. ",
"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 --.. ",
};


int main(int argc, char *argv[])
{
    int i=0;

for (i = argc-1; i >=0; i--)
{
    argv[i] = argv[i];
    printf("%s\n", argv[i]);
}

if (argc < 3)
{
    printf("Need atleast two arguments");
    return 0;
}

 for (int i = argc-1; i >= 0; i--)
{
    for (int ii = 0; ii <= SIZE; ii++)
    {
      char *pointer =  strstr(morse[ii], argv[i]);

      if ( pointer!=NULL)
      {
        printf("%c", *morse[ii]);
      }
    }
}

So if the user entered ".-" which is stored in the argv array, my for loop would go through morse and use the strstr to find ".-", and then it would print the first char which would be "a". I can't seem to successfully print out the first char in the morse array and I'm guessing it has to do with strstr.

Lescurel
  • 10,749
  • 16
  • 39
thale
  • 23
  • 4
  • Note that `strstr()` would find `.` (e in Morse) in every symbol that uses any `.` at all. You need to use a different comparator. Given the data, you should be able to use `strcmp(&morse[ii][2], argv[i])` for the comparison. – Jonathan Leffler Mar 10 '17 at 06:56

1 Answers1

1

strstr searches for any occurrence of a substring within another string. So for .- search succeeds for digit 1 (since .- can be found in 1 .----), for digit 2 (since .- can be found in 2 ..---), etc.

In order to match .- exactly you need to surround user input with spaces. In this case .- can only be found in a .-. See lines marked with (3).

for (int i = argc - 1; i > 0; i--)     // <-- (1)
{
    for (int ii = 0; ii < SIZE; ii++)  // <-- (2)
    {
        char user_letter[8];
        sprintf_s(user_letter, sizeof(user_letter), " %s ", argv[i]); // <-- (3)
        const char *pointer = strstr(morse[ii], user_letter);         // <-- (3)

        if (pointer != NULL)
        {
            printf("%c", *morse[ii]);
        }
    }
}

Other points not directly related to the question:

  • (1) - argv[0] is the invoked program path so don't really want to process it as user input
  • (2) - the morse[] array index is zero-based so the last index is SIZE - 1 and not SIZE
Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40