Hi,
I am working on a small program that converts English to Morse code and back into English. The input is read from a file specified by the user no matter which way the conversion is going. I figured out the english to morse conversion pretty easily, by just reading character by character and converting into the corresponding morse code string using a two dimensional array. However I am having trouble reading the morse strings and converting them back into english using the strcmp function. I have tried both reading character by character in a loop and concatenating and reading string by string with little luck. I am thoroughly confused and any suggestions are much more than appreciated. I will attach all the code that I have tried using up until this point. Thanks in advance for any suggestions.

this is the conversion function:

void morse_to_english(char morse_strings[91][6], FILE *outfile, FILE *infile)
{
    int count = 0;
    char character = '\0', morse[6];

    read_string(morse, infile);

    while (count < 91)
    {
        if (strcmp(morse, morse_strings[count]) == 0)
        {
            character = count;
            fprintf(outfile, "%c", character);
            count = 91;
        }
        else
        {
            count++;
        }

    }
}

The hard coded 91 is there because the morse_strings array has 91 rows.

This was my method for reading strings from the file:

void read_string (char morse[6], FILE *infile)
{
    fscanf(infile,"%s", morse);
}

and here is how I called the function in main using an end-file controlled loop:

while (!feof(infile))
        {
            morse_to_english(morse, morse_strings, outfile, infile);
            count++;
}

Like i said above all suggestions are appreciated.

Recommended Answers

All 4 Replies

And more specifically now that I have been workin on it again I am having trouble preserving the white space, newlines and spaces from the input file, in my Morse code file each Morse string is separated by a space and spaces are made up of two spaces.

Read a line
Loop
   [I]strchr()[/I] for a SPACE or EOL
   copy characters before the space to another string
   Use [I]strcmp()[/I] and loop to find the letter
   Test the next character for SPACE.  If so, output another space
   Skip to next morse character
Endloop

when you say read a line would you recommend using fgets instead of fscanf(file, "%s") to read the whole line and then loop through that line instead of reading string by string?

yes, use fgets. it gets the whole line up to the newline character or the maximum number of characters argument. fscanf, as you have it written, will get up to the first whitespace. if there's any chance of whitespace variance of your files, you will have to do more complex programming with fscanf.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.