In the following code only the first . or - are picked up and it doesn't match to any of the letters defined in the switch statements below. Any idea how I can change it to see the entire Morse letters?
#include <stdio.h>
#include<string.h>
int main (void){
char str[20]=".-/.-/.-";
int i;
char letter;
// printf("%s is %d long", str,strlen(str));
for(i=0; i<strlen(str); i++){
switch(str[i]){
/*switch statements set out decimal values for Hex digits*/
case '.-':
letter ='A';
break;
case '-...':
letter = 'B';
break;
case '-.-.':
letter = 'C';
break;
case '-..':
return 'D';
break;
case '.':
letter = 'E';
break;
case '..-.':
letter = 'F';
break;
case '--.':
letter = 'G';
break;
case '....':
letter = 'H';
break;
case '..':
letter = 'I';
break;
case '.---':
letter = 'J';
break;
case '-.-.':
letter = 'K';
break;
case '.-..':
letter = 'L';
break;
case '--':
letter = 'M';
break;
case '-.':
letter = 'N';
break;
case '---':
letter = 'O';
break;
case '.--.':
letter = 'P';
break;
case '--.-':
letter = 'Q';
break;
case '.-.':
letter = 'R';
break;
case '...':
letter = 'S';
break;
case '-':
letter = 'T';
break;
case '..-':
letter = 'U';
break;
case '...-':
letter = 'V';
break;
case '.--':
letter = 'W';
break;
case '-..-':
letter = 'X';
break;
case '-.--':
letter = 'Y';
break;
case '--..':
letter = 'Z';
break;
default:
printf("Something went wrong\n");
break;
}
}
printf("%d",letter);
}
I tried changing the single quotes '' I had initially for the Morese codes to double quotes "" for strings, but I can only pick up the first - or . in it either way.
Constructs such as
'.-'are known as multicharacter constants, which have implementation defined values (of typeint). While providing a scalar value that can be used in aswitch&case, they are hardly portable, and rarely used.By contrast,
".-"is a string (literal). As strings are not scalar values (rather comprised thereof), they cannot be used in aswitchorcase. To compare strings you can make use ofstrcmp(orstrncmp).The loop
means this
switchis operating on a single character value at a time (one of
'.','-', or'/').You will need to tokenize your initial string into substrings. This can be done destructively with
strtok, or non-destructively with functions such asstrspn/strcspn.Each substring can then be compared against every possible Morse code string to find the associated character.
Here is a cursory (incomplete) implementation using
strcspnandstrncmp.