•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the C section within the Software Development category of DaniWeb, a massive community of 397,979 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,877 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C advertiser:
This code uses a structure to map a letter to an equivalent representation of Morse code. It simply loops through either a string to encode or decode looking for text to substitute with a replacement string or character. Output is presented to the stdout.
#include <stdio.h> #include <string.h> #include <ctype.h> static const struct { const char letter, *morse; } Code[] = { { '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', "--.. " },{ ' ', " " }, }; void encode(const char *s) { size_t i, j; for ( i = 0; s[i]; ++i ) { for ( j = 0; j < sizeof Code / sizeof *Code; ++j ) { if ( toupper(s[i]) == Code[j].letter ) { printf("%s", Code[j].morse); break; } } } putchar('\n'); } void decode(const char *morse) { size_t i, j; for ( i = 0; morse[i]; ) { for ( j = 0; j < sizeof Code / sizeof *Code; ++j ) { size_t size = strlen(Code[j].morse); if ( memcmp(Code[j].morse, &morse[i], size) == 0 ) { putchar(Code[j].letter); i += size; break; } } } putchar('\n'); } int main(void) { const char text[] = "Hello world"; const char test[] = ".... . .-.. .-.. --- .-- --- .-. .-.. -.. "; encode(text); decode(test); return 0; } /* my output .... . .-.. .-.. --- .-- --- .-. .-.. -.. HELLO WORLD */
Post Comment
•
•
•
•
DaniWeb Marketplace (Sponsored Links)