0

The original code is from user . I changed it up with what I have learned so far. I can't get my output to stop printing on a new line. I will not be turning this code in as my own. I'm trying to understand it so I can write my own.

#include <stdio.h>
#include <string.h>

typedef struct{
    char* morse;
    char* letter;
}morse_table_t;

int main(void) {
    char message[100];
    
    printf("Enter phrase: ");
    fgets(message, 100, stdin);
    size_t len = strlen(message);
    if (len > 0 && message[len - 1] == '\n'){
        message[--len] = '\0';
    }

    morse_table_t table[] = { {".-", "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"}, {"-----", "0"},
                              {".----", "1"}, {"..---", "2"}, 
                              {"...--", "3"}, {"....-", "4"}, 
                              {".....", "5"}, {"-....", "6"},
                              {"--...", "7"}, {"---..", "8"}, 
                              {"----.", "9"}, {"/", "   "} };

    char* segment;
    int i;
    segment = strtok(message, " ");

    while(segment){
        for(i = 0; i < 37; i++){
            if (!strcmp(segment, table[i].morse)) puts(table[i].letter);
        }
        segment = strtok(NULL, " ");
    }

    return

Output:

Enter phrase: ... --- ...
S
O
S

What I want the output to look like:

Enter phrase: ... --- ...
SOS
  • @Johnny Mopp changing ```if (!strcmp(segment, table[i].morse)) fputs(table[i].letter, stdout);``` worked. Thank you! I'm a little sad I couldn't get it on my own :'( – Annabell_27 Nov 24 '21 at 18:37
  • Side note `message[strcspn(message, "\n")] = '\0';` can replace the lines removing the newline. – 001 Nov 24 '21 at 18:37
  • Note: More than 37 characters in [Morse Code](https://en.wikipedia.org/wiki/Morse_code#Letters,_numbers,_punctuation,_prosigns_for_Morse_code_and_non-Latin_variants) – chux - Reinstate Monica Nov 24 '21 at 18:46
  • @chux-ReinstateMonica I know this is all we need for my question. – Annabell_27 Nov 24 '21 at 18:57

1 Answers1

2

puts(table[i].letter); --> fputs(table[i].letter, stdout);.

puts() appends a '\n'.

fputs() does not.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256