Thread: About the Morse code Converter

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    10

    Post About the Morse code Converter

    I'm a newbie to C, could anyone tell me how to convert letters into morse code,vice versa.
    and the file input must be in .txt file..
    please give me a hand over this...thxthx......
    Pls contact me at [email protected]
    I'm a rookie

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    First you have to know the morse code conversions for each letter. After that it's a simple matter of substitution.

    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    May 2002
    Posts
    10
    here is part of my code...I couldn;t work out the rest of it...could you give me some comment over this?

    #include <stdio.h>
    #include <string.h>
    #include "morsetable.h"
    //#define STRINGLENGTH 7
    #define TABLESIZE 48
    #define TRUE 1
    #define FALSE 0

    //typedef char Morse[STRINGLENGTH];

    struct morseTable
    {
    char text;
    Morse morse;
    };

    typedef struct morseTable table;

    table myTable[TABLESIZE];


    void createTable(){

    myTable [0].text = 'A'; strcpy(myTable [0].morse , ".-");
    myTable [1].text = 'B'; strcpy(myTable [1].morse , "-...");
    myTable [2].text = 'C'; strcpy(myTable [2].morse , "-.-.");
    myTable [3].text = 'D'; strcpy(myTable [3].morse , "-..");
    myTable [4].text = 'E'; strcpy(myTable [4].morse , ".");
    myTable [5].text = 'F'; strcpy(myTable [5].morse , "..-.");
    myTable [6].text = 'G'; strcpy(myTable [6].morse , "--.");
    myTable [7].text = 'H'; strcpy(myTable [7].morse , "....");
    myTable [8].text = 'I'; strcpy(myTable [8].morse , "..");
    myTable [9].text = 'J'; strcpy(myTable [9].morse , ".---");
    myTable[10].text = 'K'; strcpy(myTable[10].morse , "-.-");
    myTable[11].text = 'L'; strcpy(myTable[11].morse , ".-..");
    myTable[12].text = 'M'; strcpy(myTable[12].morse , "--");
    myTable[13].text = 'N'; strcpy(myTable[13].morse , "-.");
    myTable[14].text = 'O'; strcpy(myTable[14].morse , "---");
    myTable[15].text = 'P'; strcpy(myTable[15].morse , ".--.");
    myTable[16].text = 'Q'; strcpy(myTable[16].morse , "--.-");
    myTable[17].text = 'R'; strcpy(myTable[17].morse , ".-.");
    myTable[18].text = 'S'; strcpy(myTable[18].morse , "...");
    myTable[19].text = 'T'; strcpy(myTable[19].morse , "-");
    myTable[20].text = 'U'; strcpy(myTable[20].morse , "..-");
    myTable[21].text = 'V'; strcpy(myTable[21].morse , "...-");
    myTable[22].text = 'W'; strcpy(myTable[22].morse , ".--");
    myTable[23].text = 'X'; strcpy(myTable[23].morse , "-..-");
    myTable[24].text = 'Y'; strcpy(myTable[24].morse , "-.--");
    myTable[25].text = 'Z'; strcpy(myTable[25].morse , "--..");
    myTable[26].text = '0'; strcpy(myTable[26].morse , "-----");
    myTable[27].text = '1'; strcpy(myTable[27].morse , ".----");
    myTable[28].text = '2'; strcpy(myTable[28].morse , "..---");
    myTable[29].text = '3'; strcpy(myTable[29].morse , "...--");
    myTable[30].text = '4'; strcpy(myTable[30].morse , "....-");
    myTable[31].text = '5'; strcpy(myTable[31].morse , ".....");
    myTable[32].text = '6'; strcpy(myTable[32].morse , "-....");
    myTable[33].text = '7'; strcpy(myTable[33].morse , "--...");
    myTable[34].text = '8'; strcpy(myTable[34].morse , "---..");
    myTable[35].text = '9'; strcpy(myTable[35].morse , "----.");
    myTable[36].text = '.'; strcpy(myTable[36].morse , ".-.-.-");
    myTable[37].text = ','; strcpy(myTable[37].morse , "--..--");
    myTable[38].text = ':'; strcpy(myTable[38].morse , "---...");
    myTable[39].text = ';'; strcpy(myTable[39].morse , "-.-.-");
    myTable[40].text = '?'; strcpy(myTable[40].morse , "..--..");
    myTable[41].text = '~'; strcpy(myTable[41].morse , ".----.");
    myTable[42].text = '-'; strcpy(myTable[42].morse , "-....-");
    myTable[43].text = '\\'; strcpy(myTable[43].morse , "-..-.");
    myTable[44].text = '('; strcpy(myTable[44].morse , "-.--.");
    myTable[45].text = ')'; strcpy(myTable[45].morse , "-.--.-");
    myTable[46].text = '_'; strcpy(myTable[46].morse , "..--.-");
    myTable[47].text = '"'; strcpy(myTable[47].morse , ".-..-.");

    }

    int textToMorse(char ch, Morse m){
    int i;
    for(i =0; i <=TABLESIZE; i++){
    if(ch==myTable[i].text){
    strcpy(m, myTable[i].morse);
    return 1;
    }
    }

    return 0;
    }


    int morseToText(Morse m, char* ch){

    int i;
    for(i =0; i <=TABLESIZE; i++){

    if (strcmp (m, myTable[i].morse)==0)
    {

    *ch = myTable[i].text;
    return 1;
    }
    }


    return 0;

    }
    I'm a rookie

  4. #4
    Registered User
    Join Date
    May 2002
    Posts
    10
    /*translator.h */



    #ifndef _TRANSLATOR_H

    #define _TRANSLATOR_H


    #define LINELENGTH 79
    /* need to allow for '\n' */


    void translateText(char lastChar);

    void translateMorse();

    #endif
    /* translator.h*/
    I'm a rookie

  5. #5
    Registered User
    Join Date
    May 2002
    Posts
    10
    /* translator.c */

    #include <stdio.h>
    #include <string.h>
    #include "translator.h"
    #include "morsetable.h"

    Morse m;
    void translateText(char lastChar){

    char character;
    int counter=0;
    printf("M\n");
    character=getchar();
    character=getchar();

    while(character != lastChar){
    if(textToMorse(character,m)){
    printf("%s",m);
    printf(" ");
    counter+=(strlen(m)+1);
    }
    else{
    if((character==' ')||(character=='\n')){
    counter++;
    printf(" ");
    }

    else{
    fprintf(stderr, "character unavailable: %c\n", character);
    }
    }
    if(LINELENGTH<counter){
    printf("\n");
    counter=0;
    }

    character = getchar();
    }

    }

    void translateMorse(){
    char ch;
    int num, counter = 0;

    printf("T\n");
    ch=getchar();
    while(ch!=EOF){
    ch=combine();
    if(morseToText(m, &ch) == 1){
    printf("%c",ch);
    counter++;
    }
    else{
    if(ch == ' '){
    if(LINELENGTH<counter){
    printf("\n");
    counter=0;
    }
    else{
    printf(" ");
    counter++;
    }
    }else if(ch == EOF||ch == '\n'){
    }else{
    fprintf(stderr, "invalid morse code: %s\n", m);
    }
    }
    clear();
    }
    }

    char combine(){
    int index=0;
    char character;
    character=getchar();
    while(character !=' ' && character != '\n' && character!=EOF){

    if (character!=EOF){
    m[index++]=character;
    }
    else{
    break;
    }
    character=getchar();
    }
    return character;
    }

    int clear(){

    int index=0;
    while(index <= STRINGLENGTH){
    m[index++]=NULL;
    }
    return 1;
    }
    I'm a rookie

  6. #6
    Registered User
    Join Date
    May 2002
    Posts
    10
    /*morsetable.c*/

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include "morsetable.h"

    #define TABLESIZE 48
    #define SYMBOLSIZE 12

    typedef struct morsetable{
    char characters;
    Morse morse;
    };
    struct morsetable table[TABLESIZE];

    char symbols[SYMBOLSIZE]={'.', ',', ':', ';', '?', '\'', '-', '/', '(', ')', '_', '"'};
    char code [TABLESIZE][STRINGLENGTH] = {
    ".-" , "-..." , "-.-." , "-.." , "." , "..-." , "--." , "...." , ".." , ".---" ,/*A-J*/
    "-.-" , ".-.." , "--" , "-." , "---" , ".--." , "--.-" , ".-." , "..." , "-" , /*K-T*/
    "..-" , "...-" , ".--" , "-..-" , "-.--" , "--.." , /*U-Z*/
    "-----", ".----", "..---", "...--", "....-", /*0-4*/
    ".....", "-....", "--...", "---..", "----.", /*5-9*/
    ".-.-.-", "--..--", "---...", "-.-.-", "..--..", ".----.", /*1st 6 of the symbols*/
    "-....-", "-..-.", "-.--.", "-.--.-", "..--.-", ".-..-." /*2nd 6 of the symbols*/
    };
    void createTable (){
    char counter;
    int index=0;
    for(counter = 'A'; counter <= 'Z'; counter++){
    table[index].characters = counter;
    strcpy(table[index].morse, code[index]);
    index++;
    }
    for(counter = '0'; counter <= '9'; counter++){
    table[index].characters = counter;
    strcpy(table[index].morse, code[index]);
    index++;
    }
    for(counter = 0; counter < SYMBOLSIZE; counter++){
    table[index].characters = symbols[counter];
    strcpy(table[index].morse, code[index]);
    index++;
    }
    }

    int textToMorse(char ch, Morse m){
    int num;
    ch = toupper(ch);

    for (num = 0; num <TABLESIZE; num++){
    if (ch==table[num].characters){
    strcpy(m, table[num].morse);
    return 1;
    }
    }
    return 0;
    }

    int morseToText(Morse m, char* ch){
    int num ;
    for (num =0; num< TABLESIZE; num++){
    if (strcmp (m,table [num].morse)==0){
    *ch= table[num].characters;
    return 1;
    }
    }
    return 0;
    }
    I'm a rookie

  7. #7
    Registered User
    Join Date
    May 2002
    Posts
    10
    /*morsecode.c*/
    #include <stdio.h>
    #include <ctype.h>
    #include "morsetable.h"
    #include "translator.h"

    int main(void){
    char firstChar;
    char lastChar=EOF;
    createTable();
    firstChar=toupper(getchar());
    if(firstChar=='T'){
    translateText(lastChar);
    }
    else if (firstChar='M'){
    translateMorse();
    }
    else{
    printf("The first character in the file has to be 'M' or 'F'", stderr);
    }
    return 0;
    }
    I'm a rookie

  8. #8
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Please can you use code tags when posting code.

    Are you having troubles with a specific part of your program? If so, point us in that direction, it saves reading all the source to find out whats going on.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  9. #9
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    First of all: USE CODE TAGS

    Second:
    Code:
    char symbols[SYMBOLSIZE]={'.', ',', ':', ';', '?', ''', '-', '/', '(', ')', '_', '"'};
    There are some special characters in this character array which need some attention.
    The characters ', " and \ are special characters.
    If you want to place them in a string (or character) you need to place the \ character before it:

    Code:
    char symbols[SYMBOLSIZE]={'.', ',', ':', ';', '?', '\'', '-', '/', '(', ')', '_', '\"'};

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    First off, you're making this waaaaaay too complicated. To convert a string to morse code all you have to do is read each character and convert it by printing the corresponding conversion in a struct, much as you have in the first code you posted. To convert morse code to characters you do the opposite except instead of simply reading characters you need to read each code into an array until you reach a space.
    Code:
    character: T
    
    Loop through the array of structs until you find T, then return the morse code equivalent, which is -
    Throw that into a loop and you've got the text to morse conversion, very simple. 
    
    morse code: -
    
    Loop through the array of structs using strcmp until you find the code, then return the character equivalent.
    Loop it and you have the morse to text conversion.
    
    The driver would look something like this:
    
    /* pseudocode */
    int main ( void )
    {
      int i;
      char *tok;
      /* Get the string */
      for ( i = 0; array[i] != '\0'; i++ )
        printf ( "%s ", ascii_to_morse ( array[i] ) );
      /* Get the string */
      tok = strtok ( array, " " );
      while ( tok != NULL ) {
        printf ( "%c", morse_to_ascii ( tok ) );
        tok = strtok ( NULL, " " );
      }
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  11. #11
    Registered User
    Join Date
    May 2002
    Posts
    10
    first of all....thx everone for helping...hehe
    here is the specification....I must work it out..becasue it is exam related, and the exam is coming.....
    2 The Task

    Given this notion of Text ↔ Morse translation, you are required to write a C program which will accept a Text file or a Morse Code file as input, translate the message into the opposite form, and write the translation to an output file.

    There are three components to this problem:

    – check that the input file is suitable for translation
    – translate the file, either Text → Morse or Morse →Text
    – write the translation, suitably formatted, to an output file

    3 The MorseTable Abstract Data Object

    Using the ideas of abstraction discussed in lectures, it is appropriate to model the International Morse Code table given above as an Abstract Data Object (because we only ever need ONE table). Here is the header file for the ADO. You must use this header file and you must not change it in any way – it is a contract between the client and the programmer.

    /* morsetable.h */
    /* Peter Bancroft - 1.2.02 */
    /* Morse codes are strings of up to six dots and dashes. */
    /* The Morse table pairs ASCII characters with Morse equivalents. */
    /* There is an Abstract Data Object in the MorseTable.c file */

    #ifndef _MORSETABLE_H
    #define _MORSETABLE_H

    #define STRINGLENGTH 7 /* string terminator required */

    typedef char Morse[STRINGLENGTH]; /* up to six dots and dashes */

    void createTable();
    /* pre: the table does not exist */
    /* post: a table (the ADO) is initialised with Text-Morse */

    int textToMorse(char ch, Morse m);
    /* pre: table has been initialised */
    /* post: ch is in the table, m is assigned Morse equivalent */
    /* and return 1 OR ch is not in the table, return 0 */

    int morseToText(Morse m, char* ch);
    /* pre: table has been initialised */
    /* post: m is in the table, ch is assigned text equivalent */
    /* and return 1 OR m is not in the table, return 0 */


    #endif /* _MORSETABLE_H */


    You should firstly write the implementation for the table (morsetable.c) and then test your code by writing a driver program that just translates a few individual characters. (Remember, m is a dot-dash sequence and ch is one of the 48 ASCII characters in the Morse Code table.)

    4 Input Files

    All valid input files (Text and Morse) will have a first line comprising a single letter only

    – 't' or 'T' for a Text file
    – 'm' or 'M' for a Morse Code file

    This will be immediately followed by a newline character '\n'. If there are any other characters on the first line, the file will be rejected and the program will terminate.

    Text Input: The text content of the files that your program will have to handle is not rigidly formatted, so you will need to parse the input and find ways of dealing with irregularities. Text files should contain only the 48 ASCII chars in Morse Table and all other characters are erroneous - messages should be sent to stderr and the translation continue. No words will be split across two lines but you cannot rely on correct use of spaces and newlines. Don’t forget that there are two very important invisible characters in most files – '\n' and EOF. There is a sample Text input file on the OLT pages, called mgtd.txt (with intentional erratic formatting).

    Morse Code Input: Morse Code files consist of sequences of 1-6 dots and dashes separated by one space for end of character and two spaces for end of word along with '\n' and EOF. All other characters are erroneous - messages should be sent to stderr and the translation continue. Morse codes do not split over lines but words may. You cannot rely on the correct use of spaces and newlines. There is a sample Morse Code input file on the OLT pages, called rocket.mc.

    5 Auxiliary Functions

    You can abstract away the complexity of the parsing by creating a header and an implementation file to facilitate the two processes translateText and translateMorse. The header file will look something like this.
    /* translator.h */

    #ifndef _TRANSLATOR_H
    #define _TRANSLATOR_H

    #define LINELENGTH 79 /* need to allow for '\n' */

    void translateText(char lastChar);
    void translateMorse();

    #endif

    6 Running the Program

    You should not use file pointers in your program – use redirection, e.g.

    $ morsecode < input.txt > output.mc


    7 The Main Program

    Here is an outline for the main program.

    create the morse table
    if the input file is invalid, report and exit
    else if the file is Text translateText
    else (the file is Morse) translate Morse

    8 Compiler Dependency Graph

    Your program will consist of FIVE files and the #include relationships are indicated by the following diagram
    Last edited by Amber_liam; 05-28-2002 at 10:53 AM.
    I'm a rookie

  12. #12
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Here some functions that you can use:

    1. Use fopen to open a file for reading.
    Code:
    FILE *fp;
    
    if((fp = fopen("file.txt", "r")) == NULL)
    {
      printf("Failed to open file for reading\n");
      return -1;
    }
    2. Use fgets to read a line from file.
    Code:
    char line[1024]; /* assuming 1024 is enough */
    
    while(fgets(line, 1024, fp) != NULL)
    {
      line[strlen(line)-1] = '\n'; /* remove newline character */
    }
    3. Use fclose to close the file.
    Code:
    fclose(fp);

  13. #13
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Originally posted by Monster
    Here some functions that you can use:

    2. Use fgets to read a line from file.
    Code:
    char line[1024]; /* assuming 1024 is enough */
    
    while(fgets(line, 1024, fp) != NULL)
    {
      line[strlen(line)-1] = '\n'; /* remove newline character */
    }
    A slight problem with this snippet I believe . You aren't removing the newline character, you're putting one in. Also, beware:

    A common programming error is to assume the presence of a new-line character in every string that is read into the array. A new-line character will not be present when more than n-1 characters occur before the new-line. Also, a new-line character might not appear as the last character in a file, just before end-of-file.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  14. #14
    Registered User toaster's Avatar
    Join Date
    Apr 2002
    Posts
    161
    guess this reply is too late but you can compare your comversions to my chart below to check if you should have any errors.

    Code:
    International Morse Code
    
        Letter Morse Letter Morse Digit Morse
        A      .-    N      -.    0     -----
        B      -...  O      ---   1     .----
        C      -.-.  P      .--.  2     ..---
        D      -..   Q      --.-  3     ...--
        E      .     R      .-.   4     ....-
        F      ..-.  S      ...   5     .....
        G      --.   T      -     6     -....
        H      ....  U      ..-   7     --...
        I      ..    V      ...-  8     ---..
        J      .---  W      .--   9     ----.
        K      -.-   X      -..-
        L      .-..  Y      -.--
        M      --    Z      --..
    
        Letter Morse Punctuation Mark       Morse
              .-.-  Full-stop (period)     .-.-.-
              .--.- Comma                  --..--
              .--.- Colon                  ---...
        Ch     ----  Question mark (query)  ..--..
              ..-.. Apostrophe             .----.
              --.-- Hyphen                 -....-
              ---.  Fraction bar           -..-. 
              ..--  Brackets (parentheses) -.--.-
                     Quotation marks        .-..-.
    
     If the duration of a dot is taken to be one unit then that of a dash is three units. The space
    between the components of one character is one unit, between characters is three units and
    between words seven units. To indicate that a mistake has been made and for the receiver to
    delete the last word send ........ (eight dots).
    think only with code.
    write only with source.

  15. #15
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Originally posted by Hammer

    A slight problem with this snippet I believe . You aren't removing the newline character, you're putting one in.
    Oops.....
    Code:
    line[strlen(line)-1] = '\0'; /* remove newline character */

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 23
    Last Post: 04-20-2009, 07:35 AM
  2. Problem : Threads WILL NOT DIE!!
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 04-16-2004, 01:37 PM
  3. True ASM vs. Fake ASM ????
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 04-02-2003, 04:28 AM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. funky little program - word to morse converter!
    By Brian in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 01-18-2002, 04:02 PM