User Name Password Register
DaniWeb IT Discussion Community
All
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:
Nov 20th, 2005
Views: 2,188
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.
c Syntax | 4 stars
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. static const struct
  6. {
  7. const char letter, *morse;
  8. } Code[] =
  9. {
  10. { 'A', ".- " },{ 'B', "-... " },{ 'C', "-.-. " },{ 'D', "-.. " },
  11. { 'E', ". " },{ 'F', "..-. " },{ 'G', "--. " },{ 'H', ".... " },
  12. { 'I', ".. " },{ 'J', ".--- " },{ 'K', ".-.- " },{ 'L', ".-.. " },
  13. { 'M', "-- " },{ 'N', "-. " },{ 'O', "--- " },{ 'P', ".--. " },
  14. { 'Q', "--.- " },{ 'R', ".-. " },{ 'S', "... " },{ 'T', "- " },
  15. { 'U', "..- " },{ 'V', "...- " },{ 'W', ".-- " },{ 'X', "-..- " },
  16. { 'Y', "-.-- " },{ 'Z', "--.. " },{ ' ', " " },
  17. };
  18.  
  19. void encode(const char *s)
  20. {
  21. size_t i, j;
  22. for ( i = 0; s[i]; ++i )
  23. {
  24. for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
  25. {
  26. if ( toupper(s[i]) == Code[j].letter )
  27. {
  28. printf("%s", Code[j].morse);
  29. break;
  30. }
  31. }
  32. }
  33. putchar('\n');
  34. }
  35.  
  36. void decode(const char *morse)
  37. {
  38. size_t i, j;
  39. for ( i = 0; morse[i]; )
  40. {
  41. for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
  42. {
  43. size_t size = strlen(Code[j].morse);
  44. if ( memcmp(Code[j].morse, &morse[i], size) == 0 )
  45. {
  46. putchar(Code[j].letter);
  47. i += size;
  48. break;
  49. }
  50. }
  51. }
  52. putchar('\n');
  53. }
  54.  
  55. int main(void)
  56. {
  57. const char text[] = "Hello world";
  58. const char test[] = ".... . .-.. .-.. --- .-- --- .-. .-.. -.. ";
  59. encode(text);
  60. decode(test);
  61. return 0;
  62. }
  63.  
  64. /* my output
  65. .... . .-.. .-.. --- .-- --- .-. .-.. -..
  66. HELLO WORLD
  67. */
Post Comment

Only community members can submit or comment on code snippets. You must register or log in to contribute.

DaniWeb Marketplace (Sponsored Links)
All times are GMT -4. The time now is 12:51 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC