[ create a new paste ] login | about

Link: http://codepad.org/Hskwpohy    [ raw code | fork ]

C, pasted on Feb 15:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define M_LEN 27

struct Morse {
  char code[6];
  char letter;
};

struct Morse morse[] = {
  {".-", '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'},
  {"/", ' '},
};

char get_char(char *s) {
  int i;
  for (i = 0; i < M_LEN; i++) {
    if (!strcmp(morse[i].code, s))
      return morse[i].letter;
  }
  return '*';
}

const char * get_code(char c)
{
  int i;
  for (i = 0; i < M_LEN; i++) {
    if (c == morse[i].letter)
      return morse[i].code;
  }
  return NULL;
}

void decode_msg(char *s)
{
  char *w;
  w = strtok(s," ");
  while (w != NULL) {
    putchar(get_char(w));
    w = strtok(NULL," ");
  }
  putchar('\n');
}

void enclode_msg(char *s)
{
  int i;
  // convert the input string to all upper case
  char *upper = malloc(sizeof(char) * strlen(s) + 1);
  for(i = 0; i < strlen(s); i++)
    upper[i] = toupper(s[i]);
  upper[i+1] = '\0';
  for(i = 0; i < strlen(upper); i++)
    printf("%s ", get_code(upper[i]));
  putchar('\n');
  free(upper);
}

int main(int argc, char **argv)
{
  if (argc == 1 || argc > 3) {
    fprintf(stderr,"Usage: %s [-e] string\n",argv[0]);
    return 1;
  }
  else if (!strcmp(argv[1],"-e"))
    enclode_msg(argv[2]);
  else
    decode_msg(argv[1]);
  return 0;
}


Create a new paste based on this one


Comments: