I figured out how I can translate a userinput into Morse code. It works. The only thing messing with me is that no matter what input I give, at the end of the outcome it says (null) and I do not know what I have to change in my code to get rid of it. I thought it might be the end of the array wHich can not be translated
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* tableSetup();
char* all_Cap(char sentence[]);
char* trans_to_morse(char* morse[], int b);
int main()
{
char* morse[1024];
char sentence[256];
fgets(sentence,256,stdin);
all_Cap(sentence);
int b=strlen(sentence);
for(int i=0;i<b;i++){
morse[i]=tableSetup(sentence[i]);
}
trans_to_morse(morse, b);
return (0);
}
char* tableSetup(int i){
char* table[256]={0};
table['0']="-----";
table['1']=".----";
table['2']="..---";
table['3']="...--";
table['4']="....-";
table['5']=".....";
table['6']="-....";
table['7']="--...";
table['8']="---..";
table['9']="----.";
table['A']=".-";
table['B']="-...";
table['C']="-.-.";
table['D']="-..";
table['E']=".";
table['F']="..-.";
table['G']="--.";
table['H']="....";
table['I']="..";
table['J']=".---";
table['K']="-.-";
table['L']=".-..";
table['M']="--";
table['N']="-.";
table['O']="---";
table['P']=".--.";
table['Q']="--.-";
table['R']=".-.";
table['S']="...";
table['T']="-";
table['U']="..-";
table['V']="...-";
table['W']=".--";
table['X']="-..-";
table['Y']="-.--";
table['Z']="--..";
table['.']=".-.-.-";
table[',']="--..--";
table[':']="---...";
table[';']="-.-.-.";
table['?']="..--..";
table['!']="-.-.--";
table['-']="-....-";
table['_']="..--.-";
table['(']="-.--.";
table[')']="-.--.-";
table['"']=".-..-.";
table['=']="-...-";
table['+']=".-.-.";
table['/']="-..-.";
table['@']=".--.-.";
table[' ']=".......";
return(table[i]);
}
char* all_Cap(char sentence[]){
int b=strlen(sentence);
for(int i=0;i<b;i++){
if(sentence[i]>=97 && sentence[i]<=122) sentence[i] -=32;
}
return(sentence);
}
char* trans_to_morse(char* morse[], int b){
for(int i=0;i<b;i++){
printf("%s ",morse[i]);
}
return(0);
}
Outcome:
How are you?
.... --- .-- ....... .- .-. . ....... -.-- --- ..- ..--.. (null)
Process returned 0 (0x0) execution time : 6.915 s
Press any key to continue.
Just include an initialization line that says
table[`\n`] = "";
The problem is that fgets(3)
includes the final \n
character, so you try to print it, and the table entry you have for the \n
character is NULL
as you assigned it in the declaration.
Another solution is to map table['\n'] = "\n";
so a newline is mapped into a string with just a \n
, and you'll separate the output morse code into lines, as you do with the input.