i am doing a homework project which changes a string to morse code and it should take the output of "date" linux command
//Takes a char and converts it to morse code
char *morseEncode(char x)
{
switch (x)
{
case 'a':
return ".-";
case 'b':
return "-...";
....etc
//numbers
case '0':
return ".-..";
.... etc
return "..-";
//Others,mostly for date formats
case ' ':
return " ";
case ':':
return "---... ";
case '-':
return "-....- ";
case '+':
return ".-.-.";
case '/':
return "-..-.";
//default
default:
printf("Error:Unknown Character\n");
}
}
//gets date from linux terminal command date
char *getDate()
{
char *res = (char *)malloc(100 * sizeof(char));
FILE *fp = popen("date", "r");
fgets(res, 100, fp);
res[strlen(res) - 1] = '\0';
pclose(fp);
return res;
}
char *morseCode(char *s)
{
char *str = (char *)malloc(sizeof(char) * strlen(s)+100);
for (int i = 0; s[i] != '\0'; i++)
strcat(str, morseEncode(s[i]));
return str;
}
//changes a string to all lower letters since morseEncode function is for lower letters
char *strlwr(char *str)
{
unsigned char *p = (unsigned char *)str;
while (*p)
{
*p = tolower((unsigned char)*p);
p++;
}
return str;
}
int main(int argc, char *argv[])
{
char date[100]="thu jan 2 03:08:56 +04 2020"; //OUTPUT 1
//char date[100];
//strcpy (date,getDate()); //when this isnt commented OUTPUT 2
printf("Morse Code of %s is:\t %s\n", date, morseCode(strlwr(date)));
return 0;
}
The output 1 when i send the string is -......- .---.--. -. .-..------... .-..----... --.-.-. .-.-..-...--. -..-..-..-.. which is good,but when it gets it from the function
OUTPUT 2
Morse Code of thu jan 2 03:08:56 +04 2020 is:
$��-......- .---.--. -. .-..------... .-..----... --.-.-. .-.-..-...--. -..-..-..-..
As you can see it adds some weird symbols to the output