thale
thale

Reputation: 23

Using strstr method in C with two arrays?

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.

Upvotes: 0

Views: 549

Answers (1)

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

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

Upvotes: 1

Related Questions